/**
 * 平台提供的各种常用js工具方法、参数配置；
 * v-2020.7.29
 * 数据字典静态访问文件配置参数说明：
 * 可设置dictDataBase：定义数据字典是否来源数据库
 * 1）true:实时远程请求数据库；
 * 2）false:来自同名dict-data-xxxxx.js文件)
 */
var dictDataBase=false;
var dictListMap = {};//多层Map格式：

var FormUtil = {
    /**
     * 将form值转化为JSON数据
     * @param form 传入JQuery的form对象
     * @returns
     */
    serializeJson:function(form){
        var o = {};
        $.each($(form).serializeArray(), function(index) {
            if (o[this['name']]) {
                if(''!=this['value']) {
                    o[this['name']] = o[this['name']] + "," + this['value'];
                }
            } else {
                if(''!=this['value']) {
                    o[this['name']] = this['value'];
                }
            }
        });
        return o;
    },

    cleanData:function (id){
        $(':input','#'+id)
            .not(':button, :submit, :reset, :hidden')
            .val('')
            //.removeAttr('checked')
            .removeAttr('selected');
    },

    cleanDataByClass:function (id){
        $('#'+id).find(".clean").val("");//按照样式清空；
    },

    /**
     * 用JSON数组填充form,serserializeArray反向操作，用于修改时填充数据
     * @param form	传入JQuery的form对象
     * @param data	要填充的JSON数据
     */
    fillData:function(form,data,type){
        if(data){
            $.each($(form).serializeArray(), function(index) {
                //$("input[name='"+this['name']+"']").val(data[this['name']]); //可能会影响其他页面控件值
                //$("#"+$(form).attr('id')+" #"+this['name']).val(data[this['name']]); //改用多层ID选择器，避免影响其他form控件值
                if(type=='id'){
                    var thisName="";
                    if(this['name'].indexOf(".")>=0){
                        thisName = this['name'].split(".")[1];
                    }else{
                        thisName =  this['name'];
                    }
                    if(data[thisName]){
                        $("#"+$(form).attr('id')+" #"+thisName).val(data[thisName]); //改用多层ID选择器，避免影响其他form控件值
                    }
                }else{
                    var dealName =this['name'].split('.')[1];
                    if(data[dealName]){
                        $("#"+$(form).attr('id')+" *[name='"+this['name']+"']").val(data[dealName]); //按name匹配赋值
                        if("IMG"!=$(this)[0].tagName){
                            $("#"+$(form).attr('id')+" *[name='"+this['name']+"']").attr("src",data[dealName])
                        }
                    }
                }

            });
        }
    },
    cleanDataByLoadView:function(elId){
        console.log("FormUtil.cleanDataByLoadView->",elId);
        $(elId).find("[data-name]").each(function () {
            var tagName = $(this)[0].tagName;
            switch (tagName) {
                case "IMG":
                    $(this).attr("src",strUtil.doNull($(this).attr("data-def"), ctx+"/images/def.jpg"));
                    break;
                default:
                    $(this).text('');
                    $(this).attr("data-val",'');
                    $(this).val('');
                    break;
            }
        });
    },
    /**
     * 反显表单数据 add 20160710 xhe
     * @param obj 对象别名
     * @param oj 对象值
     */
    loadView:function(vobj,oj,elId){
        // console.log("loadView obj",elId);
        var obj = eval(oj);
        try{ctx}catch(e){console.log("ctx变量检测！","页面未定义此变量"+e);return;}
        var thisCtx = ctx;
        if(!('undefined'==typeof custom_dict_ctx)){thisCtx = custom_dict_ctx;}
        if(!strUtil.isNull(elId) && elId.indexOf("view")>-1){
            FormUtil.cleanDataByLoadView(elId);
        }
        for(x in obj){
            key = x;
            value = obj[x]+'';
            if(strUtil.isNull(value)){
                //continue;
                value = strUtil.doNull(value, "");
            }
            if(!strUtil.isNull(vobj) && "#"!=vobj){
                key = vobj+"."+key;//data-name="pro.proName"情况使用
            }
            // alert(key+"-->"+value);
            var txtVal = value;
            // key = p+"."+key;
            var findObj = null;
            if(strUtil.isNull(elId)){
                findObj = $("[data-name='"+key+"']");
            }else{
                findObj = $(elId).find("[data-name='"+key+"']");
            }
            findObj.each(function(i){
                var thisObj = $(this);
                //判断是否有数据字典定义取值
                var cateEname = thisObj.attr("data-dict");
                var dataTypeTag = thisObj.attr("data-type-tag");
                var tagName = thisObj[0].tagName;
                if(undefined==cateEname || cateEname==""){
                    //add 20161212 xhe  data-dict-url="doCode=dictItemList&cateEname=userType"
                    var data_dict_url = thisObj.attr("data-dict-url");
                    cateEname = getDictCateNameByUrl(data_dict_url);

                    //add 20161213 为了适用于修改时反显的。
                    //alert(tagName + "-" +$(this).attr('type'));
                    //if("SELECT"==tagName){
                    //alert("#"+thisObj[0].id);
                    //	DictUtil.getCommonDictData("select","#"+thisObj[0].id,thisObj[0].name,thisObj.attr("data-url"),thisObj.attr("data-colmun"),value);
                    //	return;
                    //}

                }

                //data-dict-url="modelTypes=s_uctSys"
                //add 20170320 xhe控制反显数据值来自其他动态表的动态字段，必须需要定义（data-page-name、data-form-name、data-obj-name、data-colmun）或（data-dict-url、data-colmun）三个属性值
                var dataDictUrl = thisObj.attr("data-dict-url");
                //add 20171010 xhe控制动态数据显示，增加pageName，formName
                var dataObjName = thisObj.attr("data-obj-name");
                //alert("dataDictUrl="+dataDictUrl+",dataObjName="+dataObjName);
                if ('SPAN'==tagName && ( (!strUtil.isNull(dataDictUrl) && (dataDictUrl.indexOf("modelTypes=s_")>-1))   ||  !strUtil.isNull(dataObjName) ) ) {

                    var showParam = eval('(' + thisObj.attr("data-colmun") + ')');//由JSON格式字符串转换为JSON对象
                    var showValue = showParam.value;
                    var showText = showParam.text;
                    var reqUrlParam = "";
                    if(!strUtil.isNull(dataDictUrl) && (dataDictUrl.indexOf("modelTypes=s_")>-1) ){
                        //得到操作表对象java名
                        if(dataDictUrl.indexOf("doCode=")<0){
                            dataDictUrl = "doCode=dymicSql";
                        }
                        reqUrlParam = dataDictUrl+"&"+dataDictUrl.split("modelTypes=s_")[1]+".w_"+showValue+"="+value;
                    }else{
                        var pageName=thisObj.attr("data-page-name");
                        var formName=thisObj.attr("data-form-name");
                        reqUrlParam = "pageName="+pageName+"&formName="+formName+"&"+dataObjName+".w_"+showValue+"="+value;
                        var dataWhere = thisObj.attr("data-condition");//查询条件
                        if(!strUtil.isNull(dataWhere)){
                            reqUrlParam+="&"+dataWhere;
                        }
                    }
                    //alert(common_info_url+"?"+reqUrlParam);
                    $.ajax({
                        type:'get',
                        url:common_info_url+"?"+reqUrlParam,
                        //data:datas,
                        async:false,
                        dataType:'json',
                        error: function(){
                            var formId = thisObj.parents("form").eq(0).attr("id");
                            //来源于数据字典或者动态表数据的元素，必须定义id
                            var tsimis = "【"+formId+"】中";
                            alert(formId+'中SPAN返显【'+key+'】元素的请求['+reqUrlParam+']动态数据异常');
                        },
                        success: function(myData){
                            //console.log(myData);
                            var myDataObj = myData[dataObjName];
                            if(myData!=null){
                                for(col in myDataObj){
                                    if(showText == col) {
                                        thisObj.attr("data-val",value);//存储原值
                                        thisObj.text(myDataObj[col]);
                                        thisObj.val(value);
                                        break;
                                    }
                                }
                            }
                        }
                    });
                }else if(undefined!=cateEname && cateEname){
                    var fatherValue = 0;

                    var releObjTypeTag = thisObj.parent().parent().attr("data-type-tag");
                    var dataReleCode = thisObj.parent().parent().attr("data-rele-code");

                    if(!strUtil.isNull(txtVal)){
                        //处理地区数据字典级联操作
                        if(cateEname=="area") {
                            if(txtVal.substring(2,txtVal.length)!="0000") { //如果不是省
                                if(txtVal.substring(4,txtVal.length)=="00") { //判断是否是市
                                    fatherValue = txtVal.substring(0,2)+"0000";
                                } else if(Number(txtVal.substring(4,txtVal.length))>0){
                                    //暂无地级县，有区为直辖市、区
                                    if(txtVal.indexOf("110")>-1||txtVal.indexOf("120")>-1
                                        ||txtVal.indexOf("310")>-1||txtVal.indexOf("500")>-1){
                                        fatherValue = txtVal.substring(0,3)+"000";//直辖市：北京，天津，上海，重庆
                                    }else{
                                        fatherValue = txtVal.substring(0,4)+"00";//判断为地区
                                    }
                                }
                            }
                        }
                        if(dictListMap.hasOwnProperty(cateEname)){//map中有就从map中取值
                            thisObj.attr("data-val",txtVal);
                            var textContent = "";
                            if(txtVal.indexOf(",")>-1){//认为带,号就是多个
                                var valArrays = txtVal.split(",");
                                for(var i=0;i<valArrays.length;i++){
                                    var vals = valArrays[i];
                                    if(i>0){
                                        textContent += ",";
                                    }
                                    textContent += dictListMap[cateEname][vals];
                                }
                            }else{
                                textContent = dictListMap[cateEname][txtVal];
                            }
                            thisObj.text(textContent);
                            thisObj.val(textContent);
                        }else{
                            var urlAddr = "";
                            if(dictDataBase){
                                //来自数据库
                                urlAddr = thisCtx+'/dictSelect.action?cateEname='+cateEname+'&fatherValue='+fatherValue;
                            }else{
                                //来自文件，拼接cateEname名称（3.2版本后三级联动数据也产生了普通的key-value格式的数据。
                                urlAddr = thisCtx+"/js/dictData/dict-data-"+cateEname.toLowerCase()+".js";
                                // if("rele"==releObjTypeTag){
                                //     if("area"==dataReleCode){
                                //         urlAddr = ctx+"/js/dictData/jquery.cityselect-dict-data.js";
                                //     }else{
                                //         urlAddr = ctx+"/js/dictData/jquery.select-dict-data-"+dataReleCode.toLowerCase()+".js";
                                //     }
                                // }
                            }
                            console.log("loadView",urlAddr);
                            $.ajax({type:'get',async:false,dataType:'json',
                                url:urlAddr,
                                success:function(myData){
                                    //console.log(myData);
                                    if(myData){
                                        // if("rele"==releObjTypeTag){
                                        //     thisObj.attr("data-val",txtVal);
                                        //     var viewReleDivObj = thisObj.parent().parent();
                                        //     FormUtil.showcityDictDataBySpan(viewReleDivObj,myData);
                                        // }else{
                                            for(var k in myData){
                                                if(txtVal==myData[k].id){
                                                    thisObj.attr("data-val",txtVal);
                                                    thisObj.text(myData[k].text);
                                                    thisObj.val(myData[k].text);
                                                    return;
                                                }
                                            }
                                        // }
                                    }
                                },
                                error:function(){
                                    alert(cateEname+"数据字典加载失败，请检查服务器！");
                                }
                            });
                        }
                    }
                }else{
                    if("false"!=thisObj.attr("data-src-flag")){
                        thisObj.attr("data-val",value);//存储原值
                    }

                    //1.转换格式
                    var dataFormat = thisObj.attr("data-format");//格式转换
                    if(undefined!=dataFormat && txtVal){
                        try{
                            /**
                             if("fmoney"==dataFormat)txtVal = fmoney(value);//普通千分符格式
                             else if("fmoneyzhuan"==dataFormat)txtVal = moneyZhuan(value,'面议');//万元,亿单位换算
                             else if("moneyNum"==dataFormat)txtVal = moneyNum(value);//返回必须是数字
                             else if("moneyZero"==dataFormat)txtVal = moneyZero(value,'无');
                             else if("getProStatusTxt"==dataFormat)txtVal = getProStatus(value);//项目状态
                             else if("getApplyStatusTxt"==dataFormat)txtVal = getApplyStatusTxt(value);//报名状态nyt
                             else if("getApplyStatusTxtBjte"==dataFormat)txtVal = getApplyStatusTxtBjte(value);//购买状态bjte
                             else if("getPayStatusTxt"==dataFormat)txtVal = getPayStatusTxt(value);//支付状态
                             else if("getDealStatusTxtBjte"==dataFormat)txtVal = getDealStatusTxtBjte(value);//订单状态
                             else if("getBillStatusTxt"==dataFormat)txtVal = getBillStatusTxt(value);//结算状态
                             else if("getSessionStatus"==dataFormat)txtVal = getSessionStatus(value);//
                             else if("subStr"==dataFormat)txtVal = strUtil.subStr(value,strUtil.doNull(thisObj.attr("data-size"), 2));//截取
                             else if("subStr2"==dataFormat)txtVal = strUtil.subStr2(value,strUtil.doNull(thisObj.attr("data-size"), 2));//截取
                             else if("monthAndYear"==dataFormat)txtVal = strUtil.monthAndYear(value);//把月份转换，x年x月
                             else if("getPayTypeTxt"==dataFormat)txtVal = getPayTypeTxt(value);//支付方式
                             else if("getBillTxt"==dataFormat)txtVal = getBillTxt(value);//单据类型
                             else txtVal=window[dataFormat](value);**/
                            if("getDictNameByFile"==dataFormat){//add 20180627 反显支持通过数据字典标识，读取js文件取文本
                                var cateEnameText = thisObj.attr("data-dict-cate");
                                if(!strUtil.isNull(cateEnameText)){
                                    txtVal = DictUtil.getDictNameByFile(cateEnameText,0,value)
                                }else{
                                    txtVal = "undefined data-dict-cate";
                                }
                            }else if("getFormatDateSmptByLong"==dataFormat && !strUtil.isNull(value)){
                                var srcValue = obj[x];
                                var valueTypes = strUtil.getTypeByObj(srcValue);
                                var dataTypeTag = thisObj.attr("data-type-tag");
                                var defPattern = strUtil.doNull(thisObj.attr("data-format-pattern"),'yyyy-MM-dd');
                                if("Object"==valueTypes && dataTypeTag=='date'){
                                    txtVal = getFormatDateSmptByLong(srcValue.time,defPattern);
                                    thisObj.attr("data-val",txtVal);
                                }
                            }else{
                                txtVal=window[dataFormat](value);//add 20180301 其后调用自定义方法（在各自页面或者工程内mytools.js中添加反显方法）
                            }
                        }catch(e){console.log("函数["+dataFormat+"="+value+"]执行失败！可能是当前工程mytools.js中未定义！");console.log(e);}
                    }
                    //2.显示最大值，超出部分以...
                    var dataMax = thisObj.attr("data-max");
                    if(undefined!=dataMax && txtVal){
                        if(txtVal.length>dataMax*1){
                            txtVal = subStr(value,dataMax);
                            thisObj.attr("title",value);
                        }
                    }
                    //alert(tagName+"-"+thisObj.attr("data-name"));
                    //根据标签不同转换不同的。
                    var tagName = thisObj[0].tagName;
                    if('IMG'==tagName){
                        var defsrc = ctx+"/images/def.jpg";
                        var dataDefSrc=thisObj.attr("data-def");
                        if(undefined!=dataDefSrc && !strUtil.isNull(dataDefSrc)){
                            defsrc = dataDefSrc
                        }
                        thisObj.attr("src",strUtil.doNull(txtVal,defsrc));
                    }else if('A'==tagName){
                        if(!strUtil.isNull(value)&&value.indexOf("http")>-1){
                            thisObj.attr("href",value);
                        }
                    }else if('INPUT'==tagName && !strUtil.isNull(txtVal)){

                        //判断input是否是单选框，如果是将预置值与数据值相同的按钮选中
                        if($(this).attr('type')=="radio") {
                            if($(this).val()==value) {
                                $(this).attr("checked","checked");
                            }
                        }else{
                            //if($(this).attr('type')=="text") {
                            //thisObj.val(txtVal);
                            //update 20160804 xhe 页面文本框/隐藏文本框若为空则赋值，否则不赋值；
                            //thisObj.val(strUtil.doNull(thisObj.val(),txtVal));
                            thisObj.val(txtVal);
                        }
                    }else if('SELECT'==tagName){
                        //DictUtil.getCommonDictData("select","#"+thisObj[0].id,thisObj[0].name,thisObj.attr("data-url"),thisObj.attr("data-colmun"),value);
                        var releObj = thisObj.parent().parent();
                        //三级联下拉框单独处理
                        if(releObj!=null && "rele"==releObj.attr("data-type-tag")){
                            if($(this).is(".prov"))releObj.attr("rele-first-def",value);
                            if($(this).is(".city"))releObj.attr("rele-second-def",value);
                            if($(this).is(".dist"))releObj.attr("rele-third-def",value);
                            DictUtil.initThirdReleSelct(releObj);
                        }
                        thisObj.val(txtVal);
                        //alert($(thisObj).attr("id"));
                        if("selectMultiple"==thisObj.attr("data-type-tag") && !strUtil.isNull(txtVal)){
                            var multValArray = txtVal.split(",");
                            //alert($(thisObj).attr("id")+"=="+thisObj.attr("data-type-tag"));
                            //alert(txtVal+"---"+multValArray.length);
                            //txtVal = "c270745bda7d4b94904aa64dab9741d6,cffbbfcec0ec4e09967477bd3e10bc5b";
                            thisObj.multiselect('select', multValArray);//['11','22']
                            thisObj.multiselect('refresh');

                            //下面开始拼装反显multiselect之前新增保存到数据库的各种（value,text,other）内容分割拼装hidden。保证修改。
                            var dataColmun = thisObj.attr("data-colmun");
                            var multipResultId = thisObj.attr("data-multiple-result-id");//获取select定义的存放选中项结果的元素
                            var multipHiddenName = thisObj.attr("data-multiple-result-hidden-name");
                            if(!strUtil.isNull(dataColmun) && multValArray.length>0 && !strUtil.isNull(multipHiddenName)){
                                //初始化其他隐藏的反显字段
                                if(thisObj.parent().find("#"+multipResultId).length==0){
                                    //不存在存放选中项的就在其后添加一个div
                                    thisObj.after("<div id='"+multipResultId+"'></div>");
                                }
                                var multipleResultsObj = $("#"+multipResultId);
                                var showParam= eval("(" + dataColmun + ")");
                                var textName = showParam.text;
                                var valueName = showParam.value;
                                var otherStr = showParam.other;
                                var multipObjName = multipHiddenName.split(".")[0];
                                var multTextStr = obj[textName];
                                if(!strUtil.isNull(multTextStr)){
                                    var multTextArray = multTextStr.split(",");
                                    //alert(multValArray.length);
                                    var multipResultHtmls = "";
                                    for(var s=0;s<multValArray.length;s++){
                                        var muVal = multValArray[s];
                                        var muText= multTextArray[s];
                                        multipResultHtmls += "<p class='multip-group-"+muVal+"'>";
                                        multipResultHtmls += "<input type='hidden' name='"+multipHiddenName+"' multip-hidden-obj-name='"+multipHiddenName+"' text='"+muText+"' value='"+muVal+"'/>";

                                        //alert(otherStr+"--"+obj[otherStr]);
                                        //批量补充其他other中定义的属性值
                                        if(!strUtil.isNull(otherStr)){
                                            var oars = otherStr.split(",");
                                            for(var a = 0;a<oars.length;a++){
                                                var ofides =oars[a];
                                                if(!strUtil.isNull(obj[ofides])){
                                                    var ofidesVal = obj[ofides].split(",")[s];
                                                    //alert(ofides+"--"+ofidesValArrays);
                                                    var ofidesName = multipObjName+"."+ofides;
                                                    multipResultHtmls += "<input type='hidden' name='"+ofidesName+"' multip-hidden-obj-name='"+ofidesName+"' value='"+ofidesVal+"'/>";
                                                }
                                            }
                                        }
                                        multipResultHtmls += "</p>";
                                    }
                                    //alert(multipResultHtmls);
                                    multipleResultsObj.html(multipResultHtmls);
                                }
                            }
                        }
                    }else if('TEXTAREA'==tagName && value){
                        thisObj.val(txtVal);
                    }else if('DIV'==tagName && (dataTypeTag=="radio"||dataTypeTag=="checkbox"||dataTypeTag=="qrcode")){
                        //alert(thisObj.attr("data-type-tag"));
                        if(!strUtil.isNull(value)){
                            if(dataTypeTag=="radio"){
                                thisObj.find("input[type='radio'][name='"+thisObj.attr("name")+"'][value='"+value+"']").prop('checked',true);
                            }else if(dataTypeTag=="checkbox"){
                                $(this).children("input[type='checkbox']").prop('checked',false);
                                var arrCheck = value.split(',');
                                if("view"==$(this).attr("data-show-type")){
                                    //只读情况下，只要文字
                                    var viewHtmls = "";
                                    if($(this).parent().find("span[data-show]").length==0){
                                        //不存在就在其后添加一个span
                                        $(this).after("<span data-show='true'></span>");
                                    }
                                    //alert(arrCheck.length+"="+$(this).parent().find("span[data-show]").attr("data-show"));
                                    for(var m=0;m<arrCheck.length;m++){
                                        var checTextVal = $(this).find("input[type='checkbox'][value='"+arrCheck[m]+"']").attr("text-val");
                                        viewHtmls+=strUtil.doNull(checTextVal, "")+" ";
                                    }
                                    //alert(viewHtmls);
                                    $(this).hide();
                                    $(this).parent().find("span[data-show]").text(strUtil.doNull(viewHtmls,''));
                                }else{
                                    //修改反显情况下
                                    for(var m=0;m<arrCheck.length;m++){
                                        $(this).find("input[type='checkbox'][value='"+arrCheck[m]+"']").prop('checked',true);
                                    }
                                }
                            }else if(dataTypeTag=="qrcode"){
                                FormUtil.showDataQrcode(thisObj,txtVal);
                            }else{
                                thisObj.text(txtVal);
                                thisObj.val(txtVal);
                            }
                        }
                    }else{
                        thisObj.text(txtVal);
                        thisObj.val(txtVal);
                    }
                }
            });;
        }
    },
    /**
     * 显示数据的二维码图片
     * @param 操作对象
     * @param 填充的值
     * @returns
     * 单独调用方式，可参照：showDataQrcode($("#divId"),"最近一次检查时间");
     */
    showDataQrcode:function(thisObj,textVal){
        if(!strUtil.isNull(textVal)){
            thisObj.empty();
            thisObj.empty();
            var thisW=thisObj.width();
            var thisH=thisObj.height();
            if(thisW==0)thisW=60;
            if(thisH==0)thisH=60;
            thisObj.attr("data-qrcode-src",textVal);
            //alert(thisW+"--"+thisH);
            thisObj.qrcode({
                render: "table",
                width:thisW,
                height:thisH,
                text: FormUtil.toQrCodeUtf8(textVal)
            });

            //其后追加临时元素，留给点击查看大图使用。
            if(thisObj.parent().find("div[data-qrcode-large='true']").length==0){
                thisObj.after("<div class='hidden' data-qrcode-large='true'></div>");
            }

            //绑定点击事件
            thisObj.click(function(){
                //点击查看大图
                var qrcodeLargeObj =thisObj.parent().find("[data-qrcode-large='true']");
                //页面层-自定义
                qrcodeLargeObj.empty();
                qrcodeLargeObj.qrcode({
                    render: "table",
                    width:300,
                    height:300,
                    text: FormUtil.toQrCodeUtf8(thisObj.attr("data-qrcode-src"))
                });
                layer.closeAll();
                layer.open({
                    type: 1,
                    title: false,
                    area: ['342px', '342px'],
                    closeBtn: 0,
                    shadeClose: true,
                    content: "<div style='padding:20px;'>"+qrcodeLargeObj.html()+"</div>"
                });
            });
        }
    },
    //字符串格式化中文乱码问题
    toQrCodeUtf8:function(str) {
        var out, i, len, c;
        out = "";
        len = str.length;
        for(i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                out += str.charAt(i);
            } else if (c > 0x07FF) {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
            } else {
                out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
            }
        }
        return out;
    },

    /*
     * add 20180914 查看页面三级联动的数据反显
     */
    showcityDictDataBySpan:function(viewReleDivObj,myData){
        var firstObj = viewReleDivObj.find("[data-rele-type='prov']");
        var secondObj = viewReleDivObj.find("[data-rele-type='city']");
        var thirdObj = viewReleDivObj.find("[data-rele-type='dist']");
        var firstObjVal = firstObj.attr("data-val");
        var secondObjVal = secondObj.attr("data-val");
        var thirdObjVal = thirdObj.attr("data-val");
        firstObj.text("");
        secondObj.text("");
        thirdObj.text("");
        //alert(firstObjVal+"="+secondObjVal+"="+thirdObjVal);
        var ite_first_data = myData.citylist;
        for(var a in ite_first_data){
            var ite_first_key = ite_first_data[a].p.split(":")[0];
            var ite_first_val = ite_first_data[a].p.split(":")[1];
            if(firstObjVal==ite_first_key){
                firstObj.text(ite_first_val);
                var ite_second_data = ite_first_data[a].c;
                for(var b in ite_second_data){
                    var ite_second_key = ite_second_data[b].n.split(":")[0];
                    var ite_second_val = ite_second_data[b].n.split(":")[1];
                    if(secondObjVal==ite_second_key){
                        secondObj.text(ite_second_val);
                        var ite_third_data = ite_second_data[b].a;
                        for(var c in ite_third_data){
                            if(!strUtil.isNull(ite_third_data)){
                                var ite_third_key = ite_third_data[c].s.split(":")[0];
                                var ite_third_val = ite_third_data[c].s.split(":")[1];
                                //alert(thirdObjVal+"=="+ite_third_key+"-->"+ite_third_val);
                                if(thirdObjVal==ite_third_key){
                                    thirdObj.text(ite_third_val);
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    /**
     * 自定义表单元素验证【主要补充bootstrap-validator不支持的控件验证，比如特殊的data-type-tag=checkbox、radio等div】
     * @param ele 操作表单对象
     * @param options 其他配置如：{showLog:true}
     * 调用方式如下：
     * 第一步：元素定义属性【data-cuv="true" data-cuv-notempty="true" data-cuv-notempty-message="运输方式不能为空"】
     <div id="addForm_content_1_Info_Mode"  name="objName.mode" .....
     data-cuv="true" data-cuv-notempty="true" data-cuv-notempty-message="运输方式不能为空"
     data-type-tag="checkbox" data-def=""></div>
     第二步：表单submitForm1()提交处添加js
     function submitForm1(formId,tabId){
        ....
        var validate = $('#'+formId).data('bootstrapValidator').validate();
        var cuvValidata = FormUtil.customValidatorForm($('#'+formId));
        if(!validate.isValid() ||  !cuvValidata){ //如果校验不通过就返回，和bootstrapValidator结合使用
            return;
        }
        ....
    }
     */
    customValidatorForm:function(ele,options){
        var checkFlag = true;
        var checkNotArray = [];
        var showLog = strUtil.doNull(options && !strUtil.isNull(options.showLog),false);
        ele.find("[data-cuv='true']").each(function () {
            var dataMap = this.dataset;
            var $this = $(this);
            var itemObj = {};
            //1、收集信息（配置规则）
            for(var key in dataMap){
                var values = dataMap[key];
                if(key.startsWith("cuv")&&key!="cuv"){
                    var newKey = strUtil.HumpToUnderline(key).replace('cuv_','');
                    // if(showLog){console.log(key+'->'+newKey,values);}
                    itemObj[newKey]=values;
                }
                if(key=="typeTag"){
                    itemObj[strUtil.HumpToUnderline(key)]=values;
                }
            }

            //2、开始验证
            var validMessage=[];
            var typeTag = itemObj['type_tag'];
            var containerVal = $this.val();
            var containerName=$this.attr("name");
            switch (typeTag) {
                case "checkbox":
                    containerVal = $this.find("input[name='"+containerName+"']").val();
                    break;
                case "radio":
                    containerVal=$this.find("input[type='radio'][name='"+containerName+"']:checked").val();
                    break;
                default:
                    containerVal = $this.val();
                    break;
            }
            if(showLog){console.log(itemObj,typeTag,containerVal);}
            if(itemObj['notempty']){
                if(strUtil.isNull(containerVal)){
                    validMessage.push(itemObj['notempty_message']);
                    //特殊容器，注入点击事件清空提示信息，以备选中某项后隐藏上次错误提示元素和class
                    switch (typeTag) {
                        case "checkbox":
                            $this.find("input:checkbox").click(function () {
                                var checkedCount = $this.find("input:checkbox:checked").length;
                                if(checkedCount>0){
                                    var pbox =  $this.parents(".form-group");
                                    pbox.removeClass("has-feedback has-error");
                                    pbox.find("small.help-block").remove();
                                }
                            });
                        case "radio":
                            $this.find("input:radio").click(function () {
                                var checkedCount = $this.find("input:radio:checked").length;
                                if(checkedCount>0){
                                    var pbox =  $this.parents(".form-group");
                                    pbox.removeClass("has-feedback has-error");
                                    pbox.find("small.help-block").remove();
                                }
                            });
                            break;
                        default:
                            $this.change(function () {
                                if(!strUtil.isNull($(this).val())){
                                    var pbox =  $this.parents(".form-group");
                                    pbox.removeClass("has-feedback has-error");
                                    pbox.find("small.help-block").remove();
                                }
                            });
                            break;
                    }
                }
            }
            if(itemObj['stringlength']){
                var min=strUtil.doNull(itemObj['stringlength_min'],'');
                var max=strUtil.doNull(itemObj['stringlength_max'],'');
                var valLeng = containerVal.length;
                if(showLog){console.log('stringlength-->',containerName,valLeng,'['+min+','+max+']');}
                if(!strUtil.isNull(min) && !strUtil.isNull(max)){
                    if(valLeng<(min*1) || valLeng>(max*1)){
                        validMessage.push(itemObj['stringlength_message']);
                    }
                }else{
                    if(!strUtil.isNull(min) && valLeng<(min*1)){
                        validMessage.push(itemObj['stringlength_message']);
                    }else if(!strUtil.isNull(max) && valLeng>(max*1)){
                        validMessage.push(itemObj['stringlength_message']);
                    }
                }
            }
            if(itemObj['selectedmax']&&typeTag=='checkbox'){//只有复选框checkbox才支持最多选中项的校验控制
                var maxLen=strUtil.doNull(itemObj['selectedmax'],'');
                if(!strUtil.isNull(containerVal)&&!strUtil.isNull(maxLen)&&(containerVal.split(',').length>(maxLen*1))){
                    validMessage.push(itemObj['selectedmax_message']);
                }
            }
            var checkItem = {ele:$this,validRes:validMessage};
            if(showLog){console.log('checkItem',checkItem);}

            //3、父元素内显示验证不通过的提示信息对象
            var pbox =  $this.parents(".form-group");
            if(validMessage.length==0){
                pbox.find("small.help-block").remove();
                pbox.removeClass("has-feedback has-error");
            }else{
                pbox.addClass("has-feedback has-error");
                if(pbox.find("small.help-block").length>0){
                    pbox.find("small.help-block").remove();
                }
                checkNotArray.push(checkItem);
                var tipsSmallObj =$("<small style=\"display: block;\" class=\"help-block\">"+validMessage.join(',')+"</small>");
                pbox.append(tipsSmallObj);
            }
        });
        if(showLog){console.log('checkNotArray',checkNotArray);}
        if(checkNotArray.length>0){
            checkFlag=false;
        }
        console.log('FormUtil.customValidatorForm.res',checkFlag);
        return checkFlag;
    },
    /**
     * add 20200828
     * 数据导出工具方法
     * 调用方式如：FormUtil.exportDataByIusParam({'pageName':pageName,'formName':formName})
     * @param options
     */
    exportDataByIusParam:function (options) {
        console.log('FormUtil.export.options',options);
        var index_submit = layer.confirm('您确认要导出文件吗？', {btn: ['确认','取消'],closeBtn: 0,offset: '220px'}
            , function(){
                layer.close(index_submit);
                var paramMap = {};
                if(options){
                    if(options.formId){
                        paramMap = FormUtil.serializeJson(options.formId);
                    }
                    if(options.pageName){
                        paramMap['pageName']=options.pageName;
                    }
                    if(options.formName){
                        paramMap['formName']=options.formName;
                    }
                    if(options.fileName){
                        paramMap['fileName']=options.fileName;
                    }
                    if(options.tableName){
                        paramMap['tableName']=options.tableName;
                    }
                    if(options.sysName){
                        paramMap['sysName']=options.sysName;
                    }
                }
                var common_export_url = ctx+"/trans/export/data";
                var index_msg = layer.msg("正在导出文件...",{time: -1 });
                $.ajax({
                    type: 'get',
                    url: common_export_url,
                    data: paramMap,
                    dataType: "json",
                    success: function (myData) {
                        layer.close(index_msg);
                        console.log('FormUtil.export.res',myData);
                        if(myData.flag=="T"){
                            var download_url = myData['downUrl'];
                            var download_fileName = strUtil.doNull(myData['fileName'],'点此下载');
                                layer.confirm("文件导出完成！<a href='"+download_url+"' target='_blank' class='red'>"+download_fileName+"</a>", {
                                    btn: ['点击下载','取消'] //按钮
                                }, function(){
                                    window.open(download_url);
                                    layer.closeAll();
                                    index_msg=layer.msg("正在下载中...");
                                }, function(){
                                    layer.closeAll();
                                });
                        }else{
                            layer.alert(myData.msg);
                        }
                    },error:function(jqXHR, textStatus, errorThrown){
                        layer.close(index_msg);
                        console.log('getAjaxAsyncByJs.export.error',textStatus,jqXHR);
                    }
                });
            })
    }
}

//数据字典工具
var DictUtil = {
    getDictName:function(cateEname,fatherValue,key){
        try{ctx}catch(e){console.log("ctx变量检测！","页面未定义此变量"+e);return;}
        var resdata = "";
        $.ajax({
            url:ctx+'/dictSelect.action?cateEname='+cateEname+'&fatherValue='+fatherValue,
            async:false,
            type: "POST",
            dataType: "JSON",
            error:function(){
                return "";
            },
            success:function(data){
                for(var k in data){
                    if(key==data[k].id){
                        resdata = data[k].text;
                        return resdata;
                    }
                }

            }
        });
        return resdata;
    },
    getDictNameByFile:function(cateEname,fatherValue,key){
        try{ctx}catch(e){console.log("ctx变量检测！","页面未定义此变量"+e);return;}
        var resdata = "";
        var purl = "/js/dictData/dict-data-"+cateEname.toLowerCase()+".js";
        if(ctx!=undefined && ctx!=null ){
            purl = ctx+purl;
        }
        $.ajax({
            url:purl,
            //url:ctx+'/dictSelect.action?cateEname='+cateEname+'&fatherValue='+fatherValue,
            async:false,
            type: "get",
            dataType: "JSON",
            error:function(){
                return "";
            },
            success:function(data){
                for(var k in data){
                    if(key==data[k].id){
                        resdata = data[k].text;
                        return resdata;
                    }
                }

            }
        });
        return resdata;
    },
    getDictTextByFile:function(cateEname,value,types){//获取值对应的数据字典类型
        try{ctx}catch(e){console.log("ctx变量检测！","页面未定义此变量"+e);return;}
        var resdata = "";
        if(strUtil.isNull(value)){
            return resdata;
        }
        if(!dictListMap.hasOwnProperty(cateEname) || dictListMap[cateEname]==undefined){
            var purl = "/js/dictData/dict-data-"+cateEname.toLowerCase()+".js";
            if(ctx!=undefined && ctx!=null ){
                purl = ctx+purl;
            }
            console.log("getDictTextByFile",purl);
            var resultMap = {};
            $.ajax({
                url:purl,
                async:false,
                type: "get",
                dataType: "JSON",
                error:function(){
                    return "";
                },
                success:function(data){
                    for(var k in data){
                        var itemValue = data[k].id;
                        if(strUtil.isNull(itemValue)){
                            continue;
                        }
                        var itemText = data[k].text;
                        resultMap[itemValue]=itemText;
                    }
                    dictListMap[cateEname]=resultMap;
                }
            });
        }
        if(value.indexOf(",")>-1){//认为带,号就是多个
            var valArrays = value.split(",");
            for(var i=0;i<valArrays.length;i++){
                var vals = valArrays[i];
                if(i>0){
                    resdata += ",";
                }
                resdata += dictListMap[cateEname][vals];
            }
        }else{
            resdata = dictListMap[cateEname][value];
        }
        // console.log(cateEname,value,resdata,dictListMap);
        return resdata;
    },
    getDictList:function(id,url,DictType) {
        $.ajax({
            async:false,
            url: url,
            type: "get",
            data:{
                operate:'dict',
                dict_type:DictType
            },
            dataType: "html",
            error: function(){
                alert('异常错误');
            },
            success: function(data){//如果调用php成功
                $(id).empty().prepend(data);
            }
        });
    },
    getRadioList:function(id,name,url,data) {
        $.ajax({
            url: url,
            async:false,
            type: "get",
            data:data,
            dataType: "json",
            //dataType: "jsonp",
            //jsonp:'callback',
            error: function(){
                alert('异常错误');
            },
            success: function(data){
                var obj = data.rows;
                //var obj = $.parseJSON(data);
                //console.log(obj);
                for(var i = 0; i < obj.length; i++){
                    if(i==0){
                        $(id).append("<input type='radio' value='"+obj[i].itemValue+"' name='"+name+"'/>"+obj[i].itemText);
                        $("input[name='"+name+"'][value='"+obj[i].itemValue+"']").prop("checked", true);
                    }else{
                        $(id).append("<input type='radio' value='"+obj[i].itemValue+"' name='"+name+"'/>"+obj[i].itemText);
                    }
                }
            }
        });
    },
    getDictExtList:function(id,url,data) {
        $.ajax({
            url: url,
            type: "get",
            data:data,
            dataType: "json",
            async:false,
            //dataType: "jsonp",
            //jsonp:'callback',
            error: function(){
                alert('异常错误');
            },
            success: function(data){
                var obj = data.rows;
                //var obj = $.parseJSON(data);
                for(var i = 0; i < obj.length; i++){
                    $(id).append("<option value='"+obj[i].itemValue+"'>"+obj[i].itemText+"</option>");
                }
            }
        });
    },
    getCheckboxList:function(id,name,url,data) {
        $.ajax({
            url: url,
            async:false,
            type: "get",
            data:data,
            dataType: "json",
            //dataType: "jsonp",
            //jsonp:'callback',
            error: function(){
                alert('异常错误');
            },
            success: function(data){
                var obj = data.rows;
                //var obj = $.parseJSON(data);
                for(var i = 0; i < obj.length; i++){
                    $(id).append("<input type='checkbox' value='"+obj[i].itemValue+"' name='"+name+"'/>"+obj[i].itemText);
                }
            }
        });
    },
    checkSelectDict:function(id,value) {
        $(id).val(value);
    },
    checkRadioDict:function(name,value) {
        $("input[type='radio'][name='"+name+"'][value='"+value+"']").prop('checked',true);
    },
    //value必须是数组类型，否则无法处理
    checkCheckboxDict:function(name,args) {
        if(args!=null){
            for(var i=0;i<args.length;i++) {
                $("input[type='checkbox'][name='"+name+"'][value='"+args[i]+"']").prop('checked',true);
            }
        }

    },
    selectProvince:function(provinceId,url,data,provinceCode) {
        $.ajax({
            url: url,
            async:false,
            type: "POST",
            data:data,
            dataType: "text",
            error: function(){
                alert('异常错误');
            },
            success: function(data){
                var obj = $.parseJSON(data);
                for(var i = 0; i < obj.length; i++){
                    if(obj[i].id == provinceCode ){
                        $(provinceId).text(obj[i].text);
                    }
                }
            }
        });
    },
    selectCity:function(cityId,url,data,cityCode) {
        $.ajax({
            url: url,
            async:false,
            type: "POST",
            data:data,
            dataType: "text",
            error: function(){
                alert('异常错误');
            },
            success: function(data){
                var obj = $.parseJSON(data);
                for(var i = 0; i < obj.length; i++){
                    if(obj[i].id == cityCode){
                        $(cityId).text(obj[i].text);
                    }
                }
            }
        });
    },
    /**
     * 请求js文件
     * @param req_url 请求地址
     * @param spare_url 备选地址
     */
    getAjaxAsyncByJs:function(req_url,options) {
        var falg = false;
        console.log('getAjaxAsyncByJs.load',req_url);
        $.ajax({
            url:req_url,
            async:false,
            timeout : 300, //超时时间设置，单位毫秒
            type: "get",
            error:function(jqXHR, textStatus, errorThrown){
                console.log('getAjaxAsyncByJs.load.error',textStatus);
                falg = false;
            },
            success:function(data){
                falg = true;
            }
        });
        return falg;
    },
    /**
     *
     * @param objId
     * @param url
     * @param data
     * @param code
     * @param tag如果原有值不为空，是否保留原有值,true:保留
     */
    selectItemName:function(objId,url,data,code,tag) {
        $.ajax({
            url: url,
            async:false,
            type: "POST",
            data:data,
            dataType: "text",
            error: function(){
                alert('异常错误');
            },
            success: function(data){
                var obj = $.parseJSON(data);
                for(var i = 0; i < obj.length; i++){
                    if(obj[i].id == code){
                        if(tag==true){
                            $(objId).append(obj[i].text);
                        }else{
                            $(objId).text(obj[i].text);
                        }

                    }
                }
            }
        });
    },
    /**
     * 把对应数据库表值按照，指定字段拼接成select所需要的元素
     * @param id
     * @param datas 定义ajax请求参数数据
     * @param param 定义需要自动填充的属性
     */
    getDataToSelect:function(id,datas,param){
        var value = param.value;
        var text = param.text;
        var otherStr = param.other;
        var otherMap = {};
        if(otherStr){
            var oars = otherStr.split(",");
            for(var a = 0;a<oars.length;a++){
                otherMap[oars[a]]=oars[a];
            }
        }
        $(id).html("");
        $(id).append("<option value=''>--请选择--</option>");
        $.ajax({
            type:'get',
            url:common_list_url+"?doCode=dymicSql",
            data:datas,
            async:false,
            dataType:'json',
            success: function(myData){
                //console.log(myData);
                if(myData && myData.total>0){
                    for (var i=0;i<myData.total;i++){
                        var obj = myData.rows[i];
                        var optionst = "<option ";
                        //拼接值和指定的属性
                        for(key in obj){
                            if(value == key) optionst += " value='"+obj[key]+"' ";
                            if(otherMap[key]==key) optionst += key.replace(/([A-Z])/g,"-$1").toLowerCase()+"='"+obj[key]+"'";
                        }
                        //拼接text文本
                        for(key2 in obj){
                            if(text== key2) optionst += ">"+obj[key2]+"</option>";
                            continue;
                        }

                        $(id).append(optionst);
                    }
                }
            }
        });
    },
    /**
     * add xhe 2016-12-12合并之前getDictExtList和getDataToSelect方法（通吃）
     * 1、根据数据字典加载下拉框，
     * 2、支持根据指定业务obj表通过IUS加载下拉框。(指定字段拼接成select所需要的元素)
     * 3、支持默认值、选择某项元素。
     * @param type 类型（select/radio/checkbox）
     * @param id/classname 操作元素的id或者样式class名称
     * @param name 对象属性元素名称
     * @param reqUrlParam 请求url后缀参数。
     * @param showParam 数据字典使用动态表时，需要显示的对象属性值（value,text）
     * @param defVal 默认值（常用于修改反显）
     * @return map 可选，返回map类型的选项值（value->text）
     * 调用案例：
     DictUtil.getCommonDictData("radio","#addForm_testName","trpTest.testName","doCode=dictItemList&cateEname=userType","","");
     DictUtil.getCommonDictData("checkbox","#addForm_testNo","trpTest.testNo","doCode=dictItemList&cateEname=houseType","","");
     DictUtil.getCommonDictData("select","#addForm_proName","trpTest.proName","doCode=dictItemList&cateEname=memberType","","");
     DictUtil.getCommonDictData("select","#addForm_newCol","trpTest.newCol","doCode=dymicSql&modelTypes=s_trpCate","{value:'cateId',text:'cateName',other:'cateNo,cateType'}","");
     */
    getCommonDictData:function(type,id,name,reqUrlParam,showParam,defVal){
        //alert(common_list_url+"?"+reqUrlParam);
        var returnDataMap = {};
        var src="dict";//
        if(reqUrlParam.indexOf("dymicSql")>-1){
            src = "obj";//标记不是走dict静态数据字典。方便下面走else
        }
        try{ctx}catch(e){console.log("ctx变量检测！","页面未定义此变量"+e);return;}
        var thisCtx = ctx;
        if(!('undefined'==typeof custom_dict_ctx)){thisCtx = custom_dict_ctx;}
        if(src=="dict"){
            $(id).html("");

            var urlAddr = "";
            if(dictDataBase){
                if("select"==type)$(id).append("<option value=''>--请选择--</option>");
                //来自数据库
                urlAddr = common_list_url+"?"+reqUrlParam;
            }else{
                //来自文件，拼接cateEname名称
                var requrlMap = {};
                var paramArray = reqUrlParam.split("&");
                for(var p=0; p<paramArray.length; p++){
                    requrlMap[paramArray[p].split("=")[0]]=paramArray[p].split("=")[1];
                }
                cateEname = requrlMap["cateEname"];
                urlAddr = thisCtx+"/js/dictData/dict-data-"+cateEname.toLowerCase()+".js";
                console.log("req dict-data",urlAddr);
            }
            $.ajax({
                url: urlAddr,
                type: "get",
                dataType: "json",
                async:false,
                error: function(){
                    alert('数据字典['+cateEname+']项加载异常');
                },
                success: function(data){
                    //console.log(data);
                    var obj = data;
                    if(dictDataBase){
                        obj = data.rows;
                    }else{
                        obj = eval(data);
                    }
                    //控制单选按钮是否显示默认第一个选择项[data-option-first]，及自定义显示文本。
                    var defIndexRadio=0;
                    if ("radio"==type) {
                        var optionAll = $(id).attr("data-option-first");
                        if (strUtil.isNull(optionAll)) {//设置第一个默认项
                            defIndexRadio = 1;
                        }
                    }
                    var otherOptionMap = {};//其他属性
                    if(!strUtil.isNull(showParam)){
                        var showParamObj = eval('(' + showParam + ')');//由JSON格式字符串转换为JSON对象
                        // var value = strUtil.doNull(showParam.value,'');
                        // var text = strUtil.doNull(showParam.text,'');
                        // var textArray = text.split(",");
                        var otherStr = strUtil.doNull(showParamObj.other,'');
                        if(!strUtil.isNull(otherStr)){
                            var oars = otherStr.split(",");
                            for(var a = 0;a<oars.length;a++){
                                otherOptionMap[oars[a]]=oars[a];
                            }
                        }
                        // console.log(id,'showParam',showParamObj,otherOptionMap,otherStr);
                    }
                    for(var i = 0; i < obj.length; i++){
                        //console.log(obj[i]);
                        var itemValue="",itemText="",itemRemark="",itemObj=null;
                        if(dictDataBase){
                            itemValue = obj[i].itemValue;
                            itemText = obj[i].itemText;
                            itemRemark = strUtil.doNull(obj[i].itemRemark,'');
                        }else{
                            itemValue = obj[i].id;
                            itemText = obj[i].text;
                            itemRemark = strUtil.doNull(obj[i].remark,'');
                            itemObj = obj[i].item;
                        }
                        if("select"==type||type=="selectMultiple"){
                            var textBeforeStr = $(id).attr("data-option-text-before");
                            if(!strUtil.isNull(itemValue) && !strUtil.isNull(textBeforeStr)){
                                itemText=obj[i][textBeforeStr]+'-'+itemText;
                            }
                            var otherOptionAttr = "";
                            if(itemObj && itemObj!=null){
                                for(var ik in itemObj){
                                    if(otherOptionMap[ik]) {
                                        otherOptionAttr += ik.replace(/([A-Z])/g,"-$1").toLowerCase()+"='"+itemObj[ik]+"' ";
                                    }
                                }
                                // console.log(id,'otherOptionAttr',otherOptionAttr);
                            }
                            if(itemValue==defVal){
                                $(id).append("<option value='"+itemValue+"' remark='"+itemRemark+"' selected='selected' "+otherOptionAttr+"> "+itemText+"</option>");
                            }else{
                                $(id).append("<option value='"+itemValue+"' remark='"+itemRemark+"' "+otherOptionAttr+"> "+itemText+"</option>");
                            }
                        }else if ("radio"==type){
                            if(strUtil.isNull(optionAll)&&strUtil.isNull(itemValue)){
                                continue;
                            }else{
                                if(i==defIndexRadio && !strUtil.isNull(optionAll)){//设置第一个默认项
                                    itemText = optionAll;
                                }
                            }
                            //if(!dictDataBase){
                            //    defIndex=1;//文件中是从第二个默认选中（因为第一个是：--请选择--）
                            //}
                            if((i==defIndexRadio && !strUtil.isNull(optionAll)) || itemValue==defVal){
                                $(id).append("<input type='radio' value='"+itemValue+"' name='"+name+"' checked='checked'/> "+itemText+" ");
                            }else{
                                $(id).append("<input type='radio' value='"+itemValue+"' name='"+name+"'/> "+itemText+" ");
                            }
                        }else if ("checkbox"==type){
                            if(strUtil.isNull(itemValue)){
                                continue;
                            }
                            var checkHtml = "";
                            if(defVal.indexOf(itemValue)>-1) checkHtml = "checked='checked'";
                            $(id).append("<input type='checkbox' "+checkHtml+" value='"+itemValue+"' name='"+name+"' text-val='"+itemText+"'/> "+itemText+" ");
                        }
                        if(!strUtil.isNull(itemValue)){
                            returnDataMap[itemValue]=itemText;
                        }
                    }
                }
            });
        }else{

            var dataReqUrl = common_list_url;//默认请求服务端地址=本工程trans/list
            var dataServerUrl=$(id).attr("data-server-url");//元素此属性非空则用此地址
            if(!strUtil.isNull(dataServerUrl)){
                dataReqUrl=dataServerUrl;
            }
            var pageName=$(id).attr("data-page-name");
            var formName=$(id).attr("data-form-name");
            var dataObjName=$(id).attr("data-obj-name");

            if(!strUtil.isNull(pageName) && !strUtil.isNull(formName)){
                reqUrlParam = "pageName="+pageName+"&formName="+formName;
                var dataWhere = $(id).attr("data-condition");//查询条件
                if(!strUtil.isNull(dataWhere)){
                    reqUrlParam+="&"+dataWhere;
                }

            }


            showParam = eval('(' + showParam + ')');//由JSON格式字符串转换为JSON对象
            var value = showParam.value;
            var text = showParam.text;
            var textArray = text.split(",");
            var otherStr = showParam.other;
            var selected = defVal;
            var otherMap = {};
            if(otherStr){
                var oars = otherStr.split(",");
                for(var a = 0;a<oars.length;a++){
                    otherMap[oars[a]]=oars[a];
                }
            }
            $(id).html("");
            if($(id).attr("readonly")!="readonly"){
                $(id).append("<option value=''>--请选择--</option>");
            }
            $.ajax({
                type:'get',
                url:dataReqUrl+"?"+reqUrlParam,
                //data:datas,
                async:false,
                dataType:'json',
                error: function(){
                    alert('动态数据字典['+id+']项加载异常');
                },
                success: function(myData){
                    //console.log(myData);
                    if(myData && myData.total>0){
                        for (var i=0;i<myData.total;i++){
                            var obj = myData.rows[i];

                            if(obj.hasOwnProperty(dataObjName)){
                                obj = obj[dataObjName];//为了应对ius返回的结果集中涵盖实体.属性方式（因旧版是返回属性的方式）
                            }
                            var optionst = "<option ";
                            var mapKey = "";
                            var mapVal = "";
                            //拼接值和指定的属性
                            for(key in obj){
                                if(value == key){
                                    optionst += " value='"+obj[key]+"' ";
                                    mapKey = obj[key];
                                }
                                if(undefined!=selected&&selected!=''&&obj[key]==selected) optionst+=" selected='selected' ";
                                if(otherMap[key]==key) optionst += key.replace(/([A-Z])/g,"-$1").toLowerCase()+"='"+obj[key]+"'";
                            }
                            //拼接text文本
                            //for(key2 in obj){
                            var optionText = "";
                            for(var s=0;s<textArray.length;s++){
                                //if(textArray[s]== key2){
                                optionText+=obj[textArray[s]]+"-";
                                //}
                            }
                            if(!strUtil.isNull(optionText)){
                                optionText = optionText.substring(0,optionText.length-1);
                            }
                            optionst += ">"+optionText+"</option>";
                            mapVal = optionText;
                            //continue;
                            //}
                            returnDataMap[mapKey]=mapVal;
                            $(id).append(optionst);
                        }
                    }
                }
            });
        }
        return returnDataMap;
    },
    /**
     * 新增add 20170812 v2.0
     * 页面初始化全部数据字典（动态表）,支持checkbox等。
     * @param divId 为空时全局搜索，id传入#d, class传入.className
     * @returns 返回Map格式：
     * {
	 * tdxz->{"caodi":"草地","gengdi":"耕地"},
	 * userType-{org:"机构",person:"个人"}
	 * }
     */
    initDictAndDymic:function(divId){
        var findObj = null;
        if(strUtil.isNull(divId)){
            findObj = $("[data-dict-code]");
        }else{
            findObj = $(divId).find("[data-dict-code]");
        }
        findObj.each(function(){
            var dataDictCode = $(this).attr("data-dict-code");
            var dataDictCate = $(this).attr("data-dict-cate");
            var dataPageName = $(this).attr("data-page-name");
            var dataFormName = $(this).attr("data-form-name");
            var dataDictMapKey = $(this).attr("data-dict-map-key");
            var dataColmun = $(this).attr("data-colmun");
            var dictListMapKey = strUtil.doNull(strUtil.doNull(dataDictCate,dataDictMapKey), dataPageName+"-"+dataFormName);
            if(dataDictCode){
                var dictUrl = "doCode="+dataDictCode;
                if(dataDictCode=="dymicSql"){
                    dictUrl+="&modelTypes="+dataDictCate;
                    var dataWhere = $(this).attr("data-condition");//查询条件
                    if(!strUtil.isNull(dataWhere)){
                        dictUrl+="&"+dataWhere;
                    }
                    //doCode=dymicSql&modelTypes=s_trpCate
                }else{
                    dictUrl+="&cateEname="+dataDictCate;
                    //doCode=dictItemList&cateEname=userType
                }
                var tagName = $(this).attr("data-type-tag");
                var objId = $(this).attr("id");
                var objName = $(this).attr("name");
                var htmlTagName = $(this)[0].tagName.toLowerCase();
                if(htmlTagName!="span" && (tagName=="select"||tagName=="radio"||tagName=="checkbox"||tagName=="selectMultiple")){
                    if(strUtil.isNull(objId)){
                        var formId = $(this).parents("form").eq(0).attr("id");
                        //来源于数据字典或者动态表数据的元素，必须定义id
                        var tsimis = "【"+formId+"】中";
                        if(strUtil.isNull(objName)){
                            tsimis+="元素【"+$(this).attr("data-name")+"】";
                        }else{
                            tsimis+="元素【"+objName+"】";
                        }
                        alert("initDictAndDymic方法检测发现"+tsimis+"未定义ID！标签类型："+$(this)[0].tagName);
                        return;
                    }
                    var defVal = "";
                    if(!strUtil.isNull($(this).attr("data-def"))){
                        defVal = $(this).attr("data-def");
                    }
                    if("checkbox"==tagName){
                        objName = objName+"_temp";
                    }
                    //alert($(this).attr("id")+"，"+tagName+"，"+dictUrl);
                    var returnMap = DictUtil.getCommonDictData(tagName,"#"+objId,objName,dictUrl,dataColmun,defVal);
                    if(!dictListMap.hasOwnProperty(dictListMapKey)){
                        //console.log(dictListMapKey,dictListMap.hasOwnProperty(dictListMapKey));
                        //alert("returnMap=="+Object.keys(returnMap).length);
                        dictListMap[dictListMapKey]=returnMap;
                    }
                    //alert(tagName); checkbox特殊处理
                    if("checkbox"==tagName){
                        //alert($(this).html());
                        objName=$(this).attr("name");
                        //添加一个内部元素name=objName的隐藏域方面入库
                        $(this).append("<input name='"+objName+"' type='hidden' data-name='"+objName+"'/>");
                        $(this).find("input[type='checkbox']").click(function(){
                            var checktempVal = "";
                            $(this).parent().children("input[type='checkbox']:checked").each(function(){
                                checktempVal+= $(this).val()+",";
                            });
                            $(this).siblings("input[type='hidden'][name='"+objName+"']").val(checktempVal.substring(0,checktempVal.length-1));
                        });
                        var selectAllShow=strUtil.doNull($(this).attr("data-show-selected-all"),"false");
                        if("true"==selectAllShow){
                            var selectAllObjs = $("<input name='temp_selected_all' value='' type='checkbox'>");
                            $(this).prepend(selectAllObjs.prop("outerHTML")+" 全选 ");
                            console.log(selectAllObjs);
                            var selectAllVals = [];
                            $(this).find("input[type='checkbox'][name='temp_selected_all']").click(function () {
                                var thisChecked = $(this).is(":checked");
                                $(this).siblings("input[type='checkbox']").each(function(){
                                    $(this).prop('checked',thisChecked);
                                    selectAllVals.push($(this).val());
                                });
                                if(!thisChecked){
                                    selectAllVals=[];
                                }
                                $(this).siblings("input[type='hidden'][name='"+objName+"']").val(selectAllVals.join(','));
                            });
                        }
                    }else if("selectMultiple"==tagName){
                        //add 20171012 alert("多选multiple-select在此特殊处理");
                        $(this).find("option[value='']").remove();//清除getCommonDictData方法添加的空option
                        //多选multiple-select在此特殊处理//中文API地址：http://blog.csdn.net/fangzilixia/article/details/51265112
                        $(this).multiselect({
                            enableFiltering: true,//过滤
                            //buttonClass: 'btn btn-warning',//显示按钮style
                            //filterPlaceholder: 'Search for something...',
                            filterBehavior: 'text',//根据value或者text过滤
                            enableFullValueFiltering: false,//能否全字匹配 （false就是like模糊）
                            enableCaseInsensitiveFiltering: true,//不区分大小写
                            nonSelectedText: '--请选择--',//没有值的时候button显示值
                            nSelectedText: '个被选中',//有n个值的时候显示n个被选中
                            allSelectedText: '已经全部选中',//所有被选中的时候 全选（n）
                            buttonWidth: strUtil.doNull($(this).attr("data-multiple-button-width"),'60%'),//button宽度
                            maxHeight : 350,
                            numberDisplayed: strUtil.doNull($(this).attr("data-multiple-number-displayed"),5),//当超过5个标签的时候显示n个被选中
                            includeSelectAllOption: false,//全选
                            selectAllText: '选择全部',//全选的checkbox名称
                            selectAllNumber: false, //true显示allselect（6）,false显示allselect
                            onChange: function (option, checked){
                                var multipResultId = option.parent().attr("data-multiple-result-id");//获取select定义的存放选中项结果的元素
                                var dataColmun = option.parent().attr("data-colmun");
                                var multipHiddenName = option.parent().attr("data-multiple-result-hidden-name");

                                if($("#"+multipResultId).length==0){
                                    //不存在存放选中项的就在其后添加一个div
                                    option.parent().after("<div id='"+multipResultId+"'></div>");
                                }
                                var multipleResultsObj = $("#"+multipResultId);
                                if(checked){
                                    var showParam= eval("(" + dataColmun + ")");
                                    var textName = showParam.text;
                                    var valueName = showParam.value;
                                    var otherStr = showParam.other;
                                    var multipResultHtmls = "<p class='multip-group-"+option.val()+"'>";
                                    multipResultHtmls += "<input type='hidden' name='"+multipHiddenName+"' multip-hidden-obj-name='"+multipHiddenName+"' text='"+option.text()+"' value='"+option.val()+"'/>";

                                    //批量补充其他other中定义的属性值
                                    if(!strUtil.isNull(otherStr)){
                                        var multipObjName = multipHiddenName.split(".")[0];
                                        var oars = otherStr.split(",");
                                        for(var a = 0;a<oars.length;a++){
                                            var attrName = oars[a].replace(/([A-Z])/g,"-$1").toLowerCase();//把sysName格式转换sys-name
                                            var inpuNames = multipObjName+"."+oars[a];
                                            multipResultHtmls += "<input type='hidden' name='"+inpuNames+"' multip-hidden-obj-name='"+inpuNames+"' value='"+option.attr(attrName)+"'/>";
                                        }
                                    }

                                    multipResultHtmls += "</p>";
                                    multipleResultsObj.append(multipResultHtmls);
                                }else{
                                    //取消选中后，按照规则移除同类型的项
                                    multipleResultsObj.find(".multip-group-"+option.val()).remove();
                                }
                            }
                        });
                    }
                }

            }
        });

        var releFindObj = null;
        if(strUtil.isNull(divId)){
            releFindObj = $("[data-rele-code]");
        }else{
            releFindObj = $(divId).find("[data-rele-code]");
        }
        releFindObj.each(function(){
            var objId = $(this).attr("id");
            var dataDictCate = $(this).attr("data-rele-code");
            var dictListMapKey = strUtil.doNull(dataDictCate, objId);
            var returnMap = DictUtil.initThirdReleSelct(this);
            // console.log('init.rele.data',objId,dataDictCate,dictListMapKey,returnMap);
            if(Object.keys(returnMap).length>0){
                //console.log(dictListMapKey+".returnMap",returnMap);
                if(!dictListMap.hasOwnProperty(dictListMapKey) || dictListMap[dictListMapKey]==undefined){
                    dictListMap[dictListMapKey]=returnMap;
                }
            }
        });
        console.log('initDictAndDymic.data',dictListMap);
        return dictListMap;
    },
    //初始化三级联动
    initThirdReleSelct:function(obj){
        var returnDataMap = {};
        try{ctx}catch(e){console.log("ctx变量检测！","页面未定义此变量"+e);return;}
        var thisCtx = ctx;
        if(!('undefined'==typeof custom_dict_ctx)){thisCtx = custom_dict_ctx;}
        var dataReleCode = $(obj).attr("data-rele-code");
        var releFirst = $(obj).attr("rele-first");
        var releSecond = $(obj).attr("rele-second");
        var releThird = $(obj).attr("rele-third");

        var releFirstDef = $(obj).attr("rele-first-def");
        var releSecondDef = $(obj).attr("rele-second-def");
        var releThirdDef = $(obj).attr("rele-third-def");

        var releEnableDataFlag = $(obj).attr("data-rele-enable-data");

        var releUrl = "";
        if(!dataReleCode || "area"==dataReleCode){
            $(obj).citySelect({
                prov:releFirstDef,
                city:releSecondDef,
                dist:releThirdDef,
                required:false,
                nodata:"" //当子集无数据时，隐藏select
            });
        }else{
            // var formId = $(obj).parents("form").eq(0).attr("id");//获取当前元素所在父层级中的就近的formId
            // console.log("citySelect.jquery.dict-data-"+dataReleCode,formId);
            $(obj).citySelect({
                url:thisCtx+"/js/dictData/jquery.select-dict-data-"+dataReleCode+".js",
                prov:releFirstDef,
                city:releSecondDef,
                dist:releThirdDef,
                required:false,
                nodata:"" //当子集无数据时，隐藏select
            });

            //map不存在，则加载三级联动对应的科目数据map集合
            if(!dictListMap.hasOwnProperty(dataReleCode)){
                var urlAddr = thisCtx+"/js/dictData/dict-data-"+dataReleCode.toLowerCase()+".js";;
                console.log("initThirdReleData.dict-data-"+dataReleCode,urlAddr);
                $.ajax({
                    url: urlAddr,
                    type: "get",
                    dataType: "json",
                    async:false,
                    error: function(){
                        console.log('加载三级联动对应数据字典['+dataReleCode+']项加载异常');
                    },
                    success: function(data){
                        // console.log(data);
                        var obj = eval(data);
                        for(var i = 0; i < obj.length; i++){
                            // console.log(obj[i]);
                            var itemValue="",itemText="",itemRemark="";
                            itemValue = obj[i].id;
                            itemText = obj[i].text;
                            itemRemark = strUtil.doNull(obj[i].itemRemark,'');
                            if(!strUtil.isNull(itemValue)){
                                returnDataMap[itemValue]=itemText;
                            }

                        }
                    }
                });

                dictListMap[dataReleCode]=returnDataMap;
            }
        }
        return returnDataMap;
    },
    initSummernote:function(divId){
        try{ctx}catch(e){console.log("ctx变量检测！","页面未定义此变量"+e);return;}
        var thisCtx = ctx;
        if(!('undefined'==typeof custom_dict_ctx)){thisCtx = custom_dict_ctx;}
        var findObj = null;
        if(strUtil.isNull(divId)){
            findObj = $("[data-editor]");
        }else{
            findObj = $(divId).find("[data-editor]");
        }
        findObj.each(function(){
            //初始化容器（因为页面存在多个summernote，所以用class来控制。若页面只有一个即可#id来控制）
            $(this).summernote({
                lang : 'zh-CN',
                placeholder: 'write here...',
                height:60,
                minHeight: null,
                maxHeight: null,
                callbacks: {
                    //调用自定义方法，支持上传图片到服务器
                    onImageUpload: function(files) {
                        var file = files[0];
                        var objSum = $(this);
                        //alert(ctx+"==="+file);
                        var data = new FormData();
                        data.append("file", file);
                        console.log(data);
                        $.ajax({
                            data: data,
                            type: "POST",
                            url: thisCtx+"/uploadServlet",
                            cache: false,
                            contentType: false,
                            processData: false,
                            success: function(myData) {
                                if(myData){
                                    var objData = JSON.parse(myData);
                                    //alert(objData.murl);
                                    $(objSum).summernote('insertImage', objData.murl, 'image name'); // the insertImage API
                                }
                            }
                        });
                    }
                }
            });
        });
    }
}

/**
 * 将数值四舍五入(保留2位小数)后格式化成金额形式
 * @param num 数值(Number或者String)
 * @return 金额格式的字符串,如'1,234,567.45'
 * @type String
 */
function fmoney(num) {
    if(strUtil.isNull(num)){
        num = "0";
    }else{
        num = num.toString().replace(/\$|\,/g,'');
    }
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
            num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + num + '.' + cents);
}

/**
 * 金额格式化，指定null显示默认值
 * @param num
 * @param f
 * @returns {*}
 */
function fmoneyDoNull(num,f){
    if(strUtil.isNull(num)){
        return f;
    }else {
        return fmoney(num);
    }
}

/**
 * 金额转数字
 * @param v
 * @returns {*}
 */
function moneyNum(v){
    if(strUtil.isNull(v)){
        return 0;
    }
    if(isNaN(v)){
        return 0;
    }
    return v;
}

/**
 * 金额转换数字，带金额￥符号
 * @param v
 * @param f
 * @returns {*}
 */
function moneyZero(v,f){
    if(strUtil.isNull(v)){
        return f;
    }
    if(isNaN(v)){
        return f;
    }
    if(v*1>0){
        return "￥"+fmoney(v);
    }else{
        return f;
    }
}

/**
 * 金额数字转亿万等单位
 * @returns {*}
 */
function fmoneyzhuan(v,f) {
    if(isNaN(v)){
        return v;
    }
    var yi = Math.pow(10,8);
    var wan = Math.pow(10,4);
    if( v>yi || v==yi ){
        return parseFloat(v/yi).toFixed(2)+"亿";
    }else if( v>wan || v==wan ){
        return parseFloat(v/wan).toFixed(2)+"万";
    }else if(v*1>0){
        return parseFloat(v).toFixed(2)+"";
    }else{
        return f+"";
    }
}

function subStr(str,len){
    if(strUtil.isNull(str)){
        return "";
    }
    if(str.length>len){
        return str.substring(0,len)+"...";
    }else{
        return str;
    }
}
/**
 * 英文首字母大写
 * @param str
 * @returns
 */
function replaceStr(str){ // 正则法
    str = str.toLowerCase();
    var reg = /\b(\w)|\s(\w)/g; //  \b判断边界\s判断空格
    return str.replace(reg,function(m){
        return m.toUpperCase()
    });
}

/**
 * 根据文件地址获取数据字典标识名称
 * @param data_dict_url
 * @returns {string}
 */
function getDictCateNameByUrl(data_dict_url){
    var cateEname = "";
    if(undefined!=data_dict_url && data_dict_url && data_dict_url.indexOf("&")>-1){
        var dictUrlarr = data_dict_url.split("&");
        for(var i=0;i<dictUrlarr.length;i++){
            if(dictUrlarr[i].indexOf("cateEname=")>-1){
                cateEname = dictUrlarr[i].split("cateEname=")[1];
            }
        }
    }
    return cateEname;
}

/**
 * 把月份转换，x年x月
 */
function monthAndYear(val) {
    return strUtil.monthAndYear(val);
}

/**
 * 数据字典是/否转换
 * @param str
 * @returns {*}
 */
function yesOrNo(str){
    if(strUtil.isNull(str)){
        return "";
    }
    if(str.trim()=="T")return "是";
    else return "否";
}

/**
 * 字符串转成驼峰的方法  [trp_product]转成[trpProduct]
 */
function transToHumpStr(str){
    var re=/_(\w)/g;
    return str.replace(re,function ($0,$1){
        return $1.toUpperCase();
    });
}
/**
 * 移除数组指定元素
 * 调用案例：alert(removeArray(attr,"abc"))
 */
function removeArray(arr,val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == val){
            arr.splice(i, 1);
        }
    }
}

Date.prototype.format = function(format) {
    var o = {
        "M+" : this.getMonth() + 1, // month
        "d+" : this.getDate(), // day
        "h+" : this.getHours(), // hour
        "m+" : this.getMinutes(), // minute
        "s+" : this.getSeconds(), // second
        "q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
        "S" : this.getMilliseconds()
        // millisecond
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4
            - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}


/** 字符串处理区域 **/
var strUtil = {
    isNull:function (str){
        String.prototype.trim = function () {// 兼容IE8 jquery trim方法
            return this .replace(/^\s\s*/, '' ).replace(/\s\s*$/, '' );
        }
        if(!isNaN(str)){
            str = str+"";
        }
        if(null==str||undefined==str){
            return true;
        }
        if(""==str||"null"==str||"undefined"==str||JSON.stringify(str).trim().length==0){
            return true;
        }
        return false;
    },
    doNull:function(str, defVal){
        if(strUtil.isNull(str)){
            return defVal;
        }
        return str;
    },
    subStr:function(str,len){
        if(strUtil.isNull(str)){
            return "";
        }
        if(str.length>len){
            return str.substring(0,len)+"...";
        }else{
            return str;
        }
    },
    subStr2:function(str,len){
        if(strUtil.isNull(str)){
            return "";
        }
        if(str.length>len){
            return str.substring(0,len);
        }else{
            return str;
        }
    },
    //计算字符串长度 中文为3个字符英文为1
    getLength:function(str){
        return str.replace(/[\u0391-\uFFE5]/g,"aaa").length;  //先把中文替换成三个字节的英文，在计算长度
    },
    //计算可输入字节数
    getLengthOk:function(str,len){
        len = len-(str.replace(/[\u0391-\uFFE5]/g,"aaa").length);
        if(len<0){
            len = 0;
        }
        return len;
    },
    //字符大小长度转换为文件大小（带后缀），一般在getLength方法之后结合使用。
    getContentSize:function(leng){
        leng = leng*1;
        var re = leng*1;
        if (leng >= (1024 * 1024 * 1024)) {
            re = (leng/(1024 * 1024 * 1024)).toFixed(2) + " G";
        } else if (leng >= (1024 * 1024)) {
            re = (leng/(1024 * 1024)).toFixed(2) + " M";
        } else if (leng >= (1024)) {
            re = (leng/(1024)).toFixed(2)+ " KB";
        } else {
            re = leng + " 字节";
        }
        return re;
    },
    //v1 录入数据元素 v2提示信息元素 v3 限制长度
    changeLength:function(v1,v2,v3){
        var str = $("#"+v1).val();
        v3 = strUtil.getLengthOk(str,v3);
        var result = "(可输入"+v3+"个字符)";
        $("#"+v2).html(result);
    },
    /**
     * v:数字
     * f:当v=0时显示
     */
    moneyZhuan:function(v,f){
        if(isNaN(v)){
            return v;
        }
        var yi = Math.pow(10,8);
        var wan = Math.pow(10,4);
        if( v>yi || v==yi ){
            return parseFloat(v/yi).toFixed(2)+"亿";
        }else if( v>wan || v==wan ){
            return parseFloat(v/wan).toFixed(2)+"万";
        }else if(v*1>0){
            return parseFloat(v).toFixed(2)+"";
        }else{
            return f;
        }
    },
    //币种数据字典
    currency:function(str){
        if(null==str||undefined==str){
            return "人民币";
        }
        if(""==str||"null"==str||"undefined"==str||$.trim(str).length==0 ||  str=="CNY"){
            return "人民币";
        }

        if("USD"==str){
            return "美元";
        }
        if("EUR"==str){
            return "欧元";
        }
        if("GBP"==str){
            return "英镑";
        }
        if("JPY"==str){
            return "日元";
        }
        if("KRW"==str){
            return "韩元";
        }
        if("HKD"==str){
            return "港元";
        }
        if("AUD"==str){
            return "澳元";
        }
        if("CAD"==str){
            return "加元";
        }
    },
    //input非空校验并且layer.tips提示
    isNullInputTxt:function(id){
        var txtObj = $("#"+id);
        if(strUtil.isNull(txtObj.val())){
            layer.tips(txtObj.attr("tip"), "#"+id, {tips: 2});
            txtObj.focus();
            return true;
        }
        return false;
    },
    //按照t参数字符截取末尾单词
    lastStr:function(str,t){
        //alert(str);
        if(!strUtil.isNull(str)){
            if(str.indexOf(t)>-1){
                return str.substring(str.lastIndexOf(t)+1,str.length);
            }else{
                return str;
            }
        }else{
            return "";
        }
    },
    //最后一个字符之前以*格式显示（适合特殊，敏感字符格式化）
    showLast:function(str){
        return showLast(str);
    },
    //字符串中间位置替换**显示，前后字段显示对应位数
    showHideMiddle:function(str){
        return showHideMiddle(str);
    },
    //手机号格式化
    showHideByMobile:function(str){
        return showHideByMobile(str);
    },
    //js读取url参数
    getQueryString:function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    },
    //把月份转换，x年x月
    monthAndYear:function(val){
        if(strUtil.isNull(val)){
            return "";
        }else{
            if(isNaN(val)){
                return val;
            }else{
                var year =  parseInt(val/12);
                var month = parseInt(val%12);
                var ymstr = "";
                if(year>0){
                    ymstr+=year+'年';
                }
                if(month!=0){
                    ymstr+=month+'个月';
                }
                return ymstr;
            }
        }
    },
    //数据字典-自然人证件类型
    pIdentifyType:function(str){
        if("A"==str){
            return "身份证";
        }
        if("B"==str){
            return "户口簿";
        }
        if("C"==str){
            return "机动车驾驶证";
        }
        if("D"==str){
            return "护照";
        }
        if("Z"==str){
            return "其他";
        }
    },
    //数据字典-企业证件类型
    oIdentifyType:function(str){
        if("F"==str){
            return "统一社会信用代码";
        }
        if("G"==str){
            return "组织机构代码";
        }
        if("H"==str){
            return "工商注册号码";
        }
        if("I"==str){
            return "税务登记号";
        }
        if("Z"==str){
            return "其他";
        }
    },
    //数据字典-与当前人关系
    appRelation:function(str){
        if("1"==str){
            return "本人";
        }
        if("2"==str){
            return "雇佣";
        }
        if("3"==str){
            return "子女";
        }
        if("4"==str){
            return "父母";
        }
        if("5"==str){
            return "配偶";
        }
        if("6"==str){
            return "抚养";
        }
        if("7"==str){
            return "赡养";
        }
    },
    //数据字典-男女性别
    sexToCname:function(str){
        if("F"==str){
            return "女";
        }
        if("M"==str){
            return "男";
        }
    },
    //字符串内，大小字母转换下划线和小写字母
    HumpToUnderline:function(str){
        return str.replace(/([A-Z])/g,"_$1").toLowerCase();
    },
    mapToJsonStr:function(map) {
        var str = '{';
        if(Object.keys(map).length>0){
            for(var key in map) {
                str += '"'+ key+'":"'+ map[key] + '",';
            }
            str=str.substr(0,str.length-1);
        }
        str +='}';
        //console.log(str);
        return str;
    },//获取指定长度的一组，随机数数组，使用方式：var numArr = strUtil.getRandomNumArr(2,99);console.log("生成99个2位随机数数组",numArr.join(','));
    getRandomNumArr: function (len,count) {
        var arr=new Array();//原数组
        var headStr = "0000000000000000000000000";
        for (var i=0;i<count;i++){
            var num = i+1;
            var numStr = num+"";
            if(numStr.length<len){
                numStr= numStr.substr(0,len-numStr.length)+num;
            }
            arr[i]=numStr;
        }
        arr.sort(function(){ return 0.5 - Math.random(); });//打乱排序
        return arr;
    },//获取指定长度的一组随机数，使用方式：getRandomCountArr(5,100)  表示获取100以内5个随机数（可重复）
    getRandomCountArr(count,maxNum){
        var arr = [];
        for (var i=0;i<count;i++){
            var randomNum4 = Math.ceil(Math.random() * maxNum);
            arr.push(randomNum4);
        }
        return arr;
    },//解密获取存储LocalStorage
    getLocalStorage:function (key) {
        var value = localStorage.getItem(key);
        if(strUtil.isNull(value)){
            return "";
        }else{
            return $.base64.decode(value);
        }
    },//加密存储LocalStorage
    setLocalStorage:function (key,value) {
        var base64_val = $.base64.encode(value);
        localStorage.setItem(key,base64_val);
    },
    removeLocalStorage:function (key) {
        localStorage.removeItem(key);
    },//根据class样式名称前缀获取classname全名称
    getClassNameByFix:function (prefix,className) {
        if (strUtil.isNull(className)) return "";
        var objClassArry = className.split(" ");
        var objClassValue = "";
        $.each(objClassArry, function (index, item) {
            if (item.indexOf(prefix) > -1) {
                objClassValue = item;
                return;
            }
        });
        return objClassValue;
    },//年月日时间戳转化成x分钟/时/天等之前
    timeAgoStr:function(dateTimeStamp){
        var result = "刚刚";
        // dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。
        var minute=1000*60;      //把分，时，天，周，半个月，一个月用毫秒表示
        var  hour=minute*60;
        var day=hour*24;
        var week=day*7;
        var halfamonth=day*15;
        var month=day*30;
        var year=month*12;
        var  now=new Date().getTime();   //获取当前时间毫秒
        var diffValue=now - dateTimeStamp;//时间差
        if(diffValue<0){return result;}
        var  minC=diffValue / minute;  //计算时间差的分，时，天，周，月
        var  hourC=diffValue / hour;
        var  dayC=diffValue / day;
        var  weekC=diffValue / week;
        var  monthC=diffValue / month;
        var  yearC=diffValue / year;
        if(yearC>=1){
            if(yearC>=3){
                result="很久之前";
            }else{
                result="" + parseInt(yearC) + "年之前";
            }
        }else if(monthC>=1){
            result="" + parseInt(monthC) + "月之前";
        }
        else if(weekC>=1){
            result="" + parseInt(weekC) + "周之前";
        }
        else if(dayC>=1){
            result=""+ parseInt(dayC) +"天之前";
        }
        else if(hourC>=1){
            result=""+ parseInt(hourC) +"小时之前";
        }
        else if(minC>=1){
            result=""+ parseInt(minC) +"分钟之前";
        }else{
            result="刚刚";
        }
        return result;
    },//获取请求地址末尾文件名
    getReqUrlName:function () {
        var str = window.location.href;
        str = str.substring(str.lastIndexOf("/") + 1);
        return str;
    }
    ,//获取指定元素所处对象的前后对象，适用于文章详情页上一篇，下一篇快捷链接
    findArticlePreAndNexByArray:function (array,colName,colVal){
        var res=[],index=0;
        var preObj={};
        var nextObj={};
        if(array.length>0){
            for(i = 0; i < array.length; i++) {
                var obj = array[i];
                if(obj[colName].indexOf(colVal)>-1){//找到就退出循环,完成搜索
                    index=i;
                    break;
                }
            }
            if(array.length==1){
                preObj={"title":"暂无","url":""};
                nextObj={"title":"暂无","url":""};
            }else{
                if(index==0){
                    preObj={"title":"暂无","url":""};
                }else{
                    preObj=array[index-1];
                }
                if((index+1)<array.length){
                    nextObj=array[index+1];
                }else{
                    nextObj={"title":"暂无","url":""};
                }
            }
            res.push(preObj);
            res.push(nextObj);
        }
        return res;
    },//获取起止时间类型查询拼装条件
    getWhereBetweenTimeVal:function (startTime,endTime){
        var searchTime = "";
        if(strUtil.isNull(startTime) && !strUtil.isNull(endTime)){
            searchTime="-,"+endTime+" 24:00:00";
        }else if(!strUtil.isNull(startTime) && strUtil.isNull(endTime)){
            searchTime=startTime+" 00:00:00"+",";
        }else if(!strUtil.isNull(startTime) && !strUtil.isNull(endTime)){
            searchTime=startTime+" 00:00:00,"+endTime+" 24:00:00";
        }
        return searchTime;
    },
    /**
     * 根据指定日期返回 按照分割要求分割成多段数据，返回数组
     * @param startDate '2020-06-23 11:10:00'
     * @param endDate '2020-06-23 12:10:00'
     * @param amount 10
     * @param resFormat 'MM-dd hh:mm'
     * @returns {[]} Array ["06-23 11:20", "06-23 11:30", "06-23 11:40", "06-23 11:50", "06-23 12:00", "06-23 12:10"]
     */
    getSplitTimeByLen:function(startDate, endDate, amount,resFormat){
        var startTime = new Date(startDate),
            endTime = new Date(endDate),
            gap = (endTime - startTime) / amount;
            var temp = [];
            for (var i = 0; i < amount; i++) {
                startTime.setMilliseconds(startTime.getMilliseconds() + gap);
                temp[i] = new Date(startTime.getTime());
                temp[i] = temp[i].format(resFormat) //分割
            }
        return temp;
    },
    /**
     * 获取多少天之前的日期
     * @param days 10
     * @returns String 2020-02-27
     */
    getBeforeDate:function(days){
            var now=new Date().getTime();
            var ago=now-86400000*days;//一天的毫秒数为86400000
            var agoData= new Date(ago);
            var year = agoData.getFullYear();
            var mon = agoData.getMonth() + 1;
            var day = agoData.getDate();
            mon=mon<10? '0'+mon:mon;
            day=day<10? '0'+day:day;
            var date=year+'-'+mon+'-'+day;
        return date;
    },
    getTypeByObj:function(obj){
        var type  = typeof obj;
        if(type != "object"){
            return type;
        }
        return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1');
    }
};

//最后一个字符之前以*格式显示
function showLast(str) {
    if(!strUtil.isNull(str)){
        var reg = /(.*)(.)$/;
        str = str.replace(reg,function(a,b,c){
            return b.replace(/./g,"*") + c;
        });
        return str;
    }else{
        return "";
    }
}
//字符串中间位置替换*格式显示（按4除余计算）
function showHideMiddle(str){
    if(!strUtil.isNull(str)){
        var strLen = str.length;
        var xhStr = "";
        var v=Math.ceil(strLen/4);
        var reg =new RegExp('\(.{'+v+'}).*(.{'+v+'})',''); // re为/(.{3}).*(.{3})/
        for(var i=0;i<(strLen-(v*2));i++){
            xhStr+="*";//补充几个*
        }
        var resStr =  str.replace(reg,"$1"+xhStr+"$2");
        //alert(str+"\n"+reg+"\n"+xinhaoStr+"\n"+resStr);
        return resStr;
    }else{
        return "";
    }
}
//手机号格式*号影藏中间内容
function showHideByMobile(str){
    var reg = /^(\d{3})\d+(\d{4})$/;
    return str.replace(reg, "$1****$2");
}
/**
 * 添加Token,使用token提交
 */
function setToken(){
    try{ctx}catch(e){console.log("ctx变量检测！","页面未定义此变量"+e);return;}
    $.ajax({
        type:'get',
        url:ctx+'/sendPage/token?token=true',
        dataType:'text',
        async:false,
        success: function(myData){
            $("input[name='formToken']").val(myData);
            token=myData;
        }
    });
}

// //回车查询
// document.onkeydown = function mykeyDown(e) {
//     var e = e || window.event;//兼容IE8
//     if (e.keyCode == 13) {
//         var onClickValue = $(".fa-search").parent().click();
//         console.log(onClickValue);
//     }
//     return;
// };

/**
 * 获取指定日期的星期数
 * @param dateStr 字符串格式[2017-09-26]
 * @returns 星期二
 */
function getWeekDate(dateStr){
    if(strUtil.isNull(dateStr)){
        return "";
    }
    var day = new Date(Date.parse(dateStr.replace(/-/g, '/')));
    var today = new Array('星期日','星期一','星期二','星期三','星期四','星期五','星期六');
    var week = today[day.getDay()];
    return week;
}

/**
 * 转换日期字符串为指定格式字符串
 * @param dateStr 如：2018-12-20 17:08:12
 * @param pattern 如：MM-dd hh:mm
 * @returns {12-20 17:08}
 */
function getSmpFormatDateStr(dateStr,pattern) {
    if(strUtil.isNull(dateStr)){
        return "";
    }
    var dayObj  = new Date(Date.parse(dateStr.replace(/-/g, '/')));
    if(dayObj){
        return dayObj.format(pattern);
    }else{
        return dateStr;
    }
}

/**
 *转换日期对象为日期字符串
 * @param date 日期对象
 * @param isFull 是否为完整的日期数据,
 *               为true时, 格式如"2000-03-05 01:05:04"
 *               为false时, 格式如 "2000-03-05"
 * @return 符合要求的日期字符串
 */
function getSmpFormatDate(date, isFull) {
    var pattern = "";
    if (isFull == true || isFull == undefined) {
        pattern = "yyyy-MM-dd hh:mm:ss";
    } else {
        pattern = "yyyy-MM-dd";
    }
    return getFormatDate(date, pattern);
}
/**
 *转换当前日期对象为日期字符串
 * @param date 日期对象
 * @param isFull 是否为完整的日期数据,
 *               为true时, 格式如"2000-03-05 01:05:04"
 *               为false时, 格式如 "2000-03-05"
 * @return 符合要求的日期字符串
 */

function getSmpFormatNowDate(isFull) {
    return getSmpFormatDate(new Date(), isFull);
}
/**
 *转换long值为日期字符串
 * @param l long值
 * @param isFull 是否为完整的日期数据,
 *               为true时, 格式如"2000-03-05 01:05:04"
 *               为false时, 格式如 "2000-03-05"
 * @return 符合要求的日期字符串
 */
function getSmpFormatDateByLong(l, isFull) {
    return getSmpFormatDate(new Date(l), isFull);
}
/**
 *转换long值为日期字符串
 * @param l long值
 * @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss
 * @return 符合要求的日期字符串
 */
function getFormatDateByLong(l, pattern) {
    return getFormatDate(new Date(l), pattern);
}
function getFormatDateSmptByLong(l,pattern) {
    return getFormatDate(new Date(l), strUtil.doNull(pattern,"yyyy-MM-dd"));
}
/**
 *转换日期对象为日期字符串
 * @param l long值
 * @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss
 * @return 符合要求的日期字符串
 */
function getFormatDate(date, pattern) {
    if (date == undefined) {
        date = new Date();
    }
    if (pattern == undefined) {
        pattern = "yyyy-MM-dd hh:mm:ss";
    }
    return date.format(pattern);
}

function formatDate(date, format) {
    if (!date) return;
    if (!format) format = "yyyy-MM-dd";
    switch(typeof date) {
        case "string":
            if(date.indexOf(".")>0){
                date = date.substr(0,date.indexOf("."));
            }
            date = new Date(date.replace(/-/, "/"));
            break;
        case "number":
            date = new Date(date);
            break;
    }
    if (!date instanceof Date) return;
    var dict = {
        "yyyy": date.getFullYear(),
        "M": date.getMonth() + 1,
        "d": date.getDate(),
        "H": date.getHours(),
        "m": date.getMinutes(),
        "s": date.getSeconds(),
        "MM": ("" + (date.getMonth() + 101)).substr(1),
        "dd": ("" + (date.getDate() + 100)).substr(1),
        "HH": ("" + (date.getHours() + 100)).substr(1),
        "mm": ("" + (date.getMinutes() + 100)).substr(1),
        "ss": ("" + (date.getSeconds() + 100)).substr(1)
    };
    return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function() {
        return dict[arguments[0]];
    });
}

/**
 * 显示大写金额信息
 * @param currencyDigits 数字金额
 * @returns {string|*}
 */
function getChinese(currencyDigits) {
    var MAXIMUM_NUMBER = 99999999999.99;
    var CN_ZERO = "零";
    var CN_ONE = "壹";
    var CN_TWO = "贰";
    var CN_THREE = "叁";
    var CN_FOUR = "肆";
    var CN_FIVE = "伍";
    var CN_SIX = "陆";
    var CN_SEVEN = "柒";
    var CN_EIGHT = "捌";
    var CN_NINE = "玖";
    var CN_TEN = "拾";
    var CN_HUNDRED = "佰";
    var CN_THOUSAND = "仟";
    var CN_TEN_THOUSAND = "万";
    var CN_HUNDRED_MILLION = "亿";
    var CN_SYMBOL = "人民币";
    var CN_DOLLAR = "元";
    var CN_TEN_CENT = "角";
    var CN_CENT = "分";
    var CN_INTEGER = "整";

    var integral;
    var decimal;
    var outputCharacters;
    var parts;
    var digits, radices, bigRadices, decimals;
    var zeroCount;
    var i, p, d;
    var quotient, modulus;

    currencyDigits = currencyDigits.toString();
    currencyDigits = currencyDigits.replace(/,/g, "");
    currencyDigits = currencyDigits.replace(/^0+/, "");

    parts = currencyDigits.split(".");
    if (parts.length > 1) {
        integral = parts[0];
        decimal = parts[1];
        decimal = decimal.substr(0, 2);
    }
    else {
        integral = parts[0];
        decimal = "";
    }
    digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE);
    radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND);
    bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION);
    decimals = new Array(CN_TEN_CENT, CN_CENT);

    outputCharacters = "";
    if (Number(integral) > 0) {
        zeroCount = 0;
        for (i = 0; i < integral.length; i++) {
            p = integral.length - i - 1;
            d = integral.substr(i, 1);
            quotient = p / 4;
            modulus = p % 4;
            if (d == "0") {
                zeroCount++;
            }
            else {
                if (zeroCount > 0)
                {
                    outputCharacters += digits[0];
                }
                zeroCount = 0;
                outputCharacters += digits[Number(d)] + radices[modulus];
            }
            if (modulus == 0 && zeroCount < 4) {
                outputCharacters += bigRadices[quotient];
                zeroCount = 0;
            }
        }
        outputCharacters += CN_DOLLAR;
    }

    if (decimal != "") {
        for (i = 0; i < decimal.length; i++) {
            d = decimal.substr(i, 1);
            if (d != "0") {
                outputCharacters += digits[Number(d)] + decimals[i];
            }
        }
    }

    if (outputCharacters == "") {
        outputCharacters = CN_ZERO + CN_DOLLAR;
    }
    if (decimal == "") {
        outputCharacters += CN_INTEGER;
    }
    outputCharacters = outputCharacters;
    return outputCharacters;
}

/**
 * 兼容IE8 console方法
 */
window.console = window.console || (function () {
    var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile
        = c.clear = c.exception = c.trace = c.assert = function () { };
    return c;
})();


/**
 * ***********************************************************
 * 以下是合并分页js，来源之前biztools.js文件全部内容。
 */
var version = "/common/plateform/base";
window.onerror = function(message, url, linenumber) {
    //接受三个参数,分别是错误信息,错误页面的url和错误行号
    //收集系统、浏览器信息，连同错误信息一起发给服务器
    //怎么发给服务器就随你啦,ajax/beacon都行
    console.log(message);
    console.log(url);
    // console.log(linenumber);
}
//删除table内所有tr
function deleteAllRow(tablename) {
    var tb = document.getElementById(tablename);

    if (tb) {
        var rowNum = tb.rows.length;
        for (i = 1; i < rowNum; i++) {
            tb.deleteRow(i);
            rowNum = rowNum - 1;
            i = i - 1;
        }
    }
}
function formReset(formName) {
    // document.getElementById("myForm").name.disabled=false;
    document.getElementById(formName).reset();
}
window.onpopstate = function(event) {
    if (event && event.state) {
        document.title = event.state.title;
        $('#main-tzba').html(event.state.html);
    }
}
//window.onpopstate = function(event){
//	if((event || window.event) && event.state){
//		document.title = event.state.title;
//		$("#main").html(event.state.html);
//	}
//};

/**
 * 处理前台openRouter方法报错的情况
 */
var bootStrapJs = "";
function refreshBootStrap() {
    if (!bootStrapJs) {
        $.ajax({
            url: ctx+version + "/bootstrap/bootstrap.min.js?" + Math.random(),
            cache: false,
            async: false,
            success: function(js) {
                bootStrapJs = js;
            }
        });
    }
    window.eval(bootStrapJs);
    log("执行了");
}
var pageObj = {
    currentPage: 1,
    url: ""
}
/**
 * 通过url来区分不同的分页对象
 * @param url
 */
function list_url(url) {
    //如果是属于当前的分页
    if (pageObj["url"] && pageObj["url"] == url) {

        return pageObj.currentPage;

    } else {
        pageObj["currentPage"] = 1;
        pageObj["url"] = url;
        return pageObj["currentPage"];
    }
}
var pageObj = {
    currentPage: 1,
    url: ""
}
/**
 * 通过url来区分不同的分页对象
 * @param url
 */
function getCurrentPage(url,rows) {
    pageObj.rows = rows;
    //如果是属于当前的分页
    if (pageObj["url"] && pageObj["url"] == url) {

//        return pageObj.currentPage;
        return  "&page="+pageObj.currentPage+"&rows="+pageObj.rows;

    } else {
        if(sessionStorage.getItem("page")){
            pageObj["currentPage"]=sessionStorage.getItem("page");
            sessionStorage.clear();
        }else{
            pageObj["currentPage"] = 1;
        }

        pageObj["url"] = url;
//        return pageObj["currentPage"];
        return  "&page="+pageObj.currentPage+"&rows="+pageObj.rows;
    }
}


/**
 * 生成分页
 *  var option= {
				   ele:$("#pageList")[0],
				   total:myDate.total,
				   fn:getTableList(),
				   url:url
			   }
 * @param ele
 * @param total
 * @param fn
 */
function generatePages(obj) {
    var option = {};
    if (obj.total == '0' || obj.total == 0) {
        option.currentPage = 1;
        pageObj["currentPage"] = 1;

    } else {
        option.currentPage = pageObj.currentPage;
    }

    //设置分页总数
    option.totalPages = getTotalPages(obj.total);
    //设置bootStrap版本
    option.bootstrapMajorVersion = 3;
    //设置对齐方式
    option.alignment = "center";

    //点击页码时的回调函数
    option.onPageClicked = function(event, originalEvent, type, page) {
        pageObj["currentPage"] = page;
        // console.log('onPageClicked',event,originalEvent,type,page,obj);
        if(strUtil.isNull(obj.fnParam)){//字符类型参数：当多个参数英文逗号分隔
            obj.fn();
        }else{
            obj.fn(obj.fnParam);//分页支持参数
        }
    }

    // 补充分页提示及控制 add by 2020-03-24
    //切换每页显示行数后（select控件）
    option.onPageControlChang = function(event, originalEvent, type, page) {
        var thisPageSize = $(this).val();
        myPage = thisPageSize;
        pageObj["currentPage"] = 1;
        pageObj["rows"] = myPage;
        if(strUtil.isNull(obj.fnParam)){
            obj.fn();
        }else{
            obj.fn(obj.fnParam);//分页支持参数
        }

    }
    //总记录数
    option.totalRows=obj.total;
    //每页记录条数
    option.pageSize=pageObj.rows;
    //只要配置了就启用，可供选择的每页的记录数 【pageList:[10,20,50]】
    if(obj.pageList){
        option.pageList=obj.pageList;
    }
    //是否显示日志
    if(obj.showLog){
        option.showLog = obj.showLog;
        console.log('generatePages.option',option);
    }
    //防止分页出错
    if ($(obj.ele).hasOwnProperty("bootstrapPaginator")) {
        $(obj.ele).bootstrapPaginator(option)
    } else {
       getBootStrapPaginator();

        $(obj.ele).bootstrapPaginator(option)
    }
}
pageObj["BootStrapPaginator"] = null;

function getBootStrapPaginator() {
    try{ctx}catch(e){console.log("ctx变量检测！","页面未定义此变量"+e);return;}
    if (pageObj["BootStrapPaginator"]) {
        window.eval(pageObj["BootStrapPaginator"]);
    } else {
        $.ajax({
            type: "get",
            url: ctx+version + "/utils/bootstrap-paginator.js#",
            async: false,
            success: function(msg) {
                pageObj["BootStrapPaginator"] = msg;
                window.eval(msg);
            }
        });

    }

}

/***
 * 获取总的分页数
 */
function getTotalPages(total) {
    if(total==0){
        return 1;
    }
    var totalString = "" + total / pageObj.rows;

    totalString = totalString.split(".");
    if (totalString.length > 1) {
        total = Number(totalString[0]) + 1;
    } else {
        total = Number(totalString[0]);
    }

    return total;

}

function log(value) {
    console.log(value);
}

/**
 * 对Date的扩展，将 Date 转化为指定格式的String
 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符
 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 * eg:
 * (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
Date.prototype.pattern = function(fmt){
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    var week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt))
    {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt))
    {
        fmt = fmt.replace(RegExp.$1, (
            (RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o)
    {
        if (new RegExp("(" + k + ")").test(fmt))
        {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(
                ("" + o[k]).length)));
        }
    }
    return fmt;
}

var currentTable = "";
var tableHeadArray = [];
var tdCount = 1;
var currentTableEle = "null";
/**
 * tableEle:tableId
 * cellNum:插入的单元格数字
 * insertHtml:插入的内容
 */
function insertCustomCell(cellNum,insertHtml){
    var cell = currentTable.insertCell(cellNum);
    var tempTable = $(currentTable).parents("table")[0]
    if(currentTableEle=='null' || currentTableEle.id != tempTable.id){
        currentTableEle = tempTable;
        tdCount = 1;
        tableHeadArray = [];

    }

    //需要获取到当前单元格的表头
    var tableHead = $($(currentTable).parents("table")[0]).find(".active").find("th");
    if(tableHead && tableHead[0]){}
    else{
        tableHead =$($(currentTable).parents("table")[0]).find(".active").find("td");
    }

    if(!tableHead[0]){
        tableHead =$($(currentTable).parents("table")[0]).find("td");
    }
    if(!tableHead[0]){
        tableHead =$($(currentTable).parents("table")[0]).find("th");
    }

    var curentTableHeadLength = tableHead.length;

    var tableCell = tableHead[cellNum];

    var currnetEleHeight = 0;
    if(tableCell.width){
        currnetEleHeight = tableCell.width;
        cell.width = tableCell.width;
    }
    else{

        currnetEleHeight = cell.offsetWidth;
    }
    currnetEleHeight = cell.offsetWidth-20;

    //如果当亲的单元格序号小余table的head数量, 并且统计数==1
    if(!tableHeadArray[cellNum] && tdCount==1){
        tableHeadArray[cellNum] = currnetEleHeight;
    }else{
        currnetEleHeight = tableHeadArray[cellNum];
        tdCount++;
    }

    cell.style.overflow = "hidden";
    if(!insertHtml || !$.trim(insertHtml)){
        insertHtml = "";
    }
    cell.innerHTML = '<div title='+insertHtml+' style="white-space:nowrap;width:'+currnetEleHeight+'px">'+insertHtml+'</div>';
}

function insertHtmlToCell(cellNum,insertHtml,title){
    var cell = currentTable.insertCell(cellNum);
    var tempTable = $(currentTable).parents("table")[0]
    if(currentTableEle=='null' || currentTableEle.id != tempTable.id){
        currentTableEle = tempTable;
        tdCount = 1;
        tableHeadArray = [];
    }

    //需要获取到当前单元格的表头
    var tableHead = $($(currentTable).parents("table")[0]).find(".active").find("th");
    if(tableHead && tableHead[0]){}
    else{
        tableHead =$($(currentTable).parents("table")[0]).find(".active").find("td");
    }

    if(!tableHead[0]){
        tableHead =$($(currentTable).parents("table")[0]).find("td");
    }
    if(!tableHead[0]){
        tableHead =$($(currentTable).parents("table")[0]).find("th");
    }

    var curentTableHeadLength = tableHead.length;

    var tableCell = tableHead[cellNum];

    var currnetEleHeight = 0;
    if(tableCell.width){
        currnetEleHeight = tableCell.width;
        cell.width = tableCell.width;
    }
    else{

        currnetEleHeight = cell.offsetWidth;
    }
    currnetEleHeight = cell.offsetWidth-20;

    //如果当亲的单元格序号小余table的head数量, 并且统计数==1
    if(!tableHeadArray[cellNum] && tdCount==1){
        tableHeadArray[cellNum] = currnetEleHeight;
    }else{
        currnetEleHeight = tableHeadArray[cellNum];
        tdCount++;
    }

    cell.style.overflow = "hidden";
    if(!insertHtml || !$.trim(insertHtml)){
        insertHtml = "";
    }
    //cell.innerHTML = '<div title='+insertHtml+' style="white-space:nowrap;width:'+currnetEleHeight+'px">'+insertHtml+'</div>';
    cell.innerHTML = '<div title='+title+' style="white-space:nowrap;width:'+currnetEleHeight+'px">'+insertHtml+'</div>';
}

